Learn String Class in Java Quick in 20 Minutes

digitization, transformation, binary

String Class in Java:

Java string represents character String. A quoted string is a value of type String.  All string literals (example -“Java”) is an instance of this class. Strings are constant, their values can not be changed after they are created. This is why String is an immutable class.

In another way every String class is final and it can not be subclassed. Java String is a very important class to carry out day to day coding.A java String is not null-terminated character array.

Ads code goes here

The String class represents sequences of characters. Once a String object is created, it is immutable. In other words, the sequence of characters that a String represents cannot be changed after it is created. The StringBuffer class, on the other hand, represents a sequence of characters that can be changed. StringBuffer objects are used to perform computations on String objects.

The String class includes a number of utility methods, such as methods for fetching individual characters or ranges of contiguous characters, for translating characters to upper- or lowercase, for searching strings, and for parsing numeric values in strings.

String literals are compiled into String objects. Where a String literal appears in an expression, the compiled code contains a String object. If s is declared as String, the following two expressions are identical:

a.equals("ABC");
"ABC".equals(a);

The string concatenation operator implicitly creates String objects.

These values of type String are known as String but underlying they are objects. The class is a predefined class that is automatically available in our java code.

Three characters of String

  1. String is an Object in Java –  Java implements String as Object.
  2. String class is final – String class  is final in java and we can not extend a String class. This feature helps java in performance optimazation.
  3. String is Immutable-  We can not alter a string, once it is created. Any alternation to the string creates a fresh String object and leaves the original intact.

Three best books on String

The class structure of class String is given as

public final class java.lang.String extends java.lang.Object {
public String();
public String(byte[] bytes); 
public String(byte[] bytes, String enc);
public String(byte[] bytes, int offset, int length); 
public String(byte[] bytes, int offset,int length, String enc);
public String(byte[] lowbytes, int hibyte);
public String(byte[] lowbytes, int hibyte,int offset, int count);
public String(char[] value);
public String(char[] value, int offset, int;
public String(String value);
public String(StringBuffer buffer);
public static String copyValueOf(char data[]);
public static String copyValueOf(char data[], int offset, int count);
public static String valueOf(boolean b);
public static String valueOf(char c);
public static String valueOf(char[] data);
public static String valueOf(char[] data, int offset, int count);
public static String valueOf(double d);
public static String valueOf(float f);
public static String valueOf(int i);
public static String valueOf(long l);
public static String valueOf(Object obj);
public char charAt(int index);
public int compareTo(String anotherString);
public String concat(String str);
public boolean endsWith(String suffix);
public boolean equals(Object anObject);
public boolean equalsIgnoreCase(String anotherString);
public byte[] getBytes(); 
public byte[] getBytes(String enc); 
public void getBytes(int srcBegin, int srcEnd,byte[] dst, int dstBegin); 
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin);
public int hashCode();
public int indexOf(int ch);
public int indexOf(int ch, int fromIndex);
public int indexOf(String str);
public int indexOf(String str, int fromIndex);
public native String intern();
public int lastIndexOf(int ch);
public int lastIndexOf(int ch, int fromIndex);
public int lastIndexOf(String str);
public int lastIndexOf(String str, int fromIndex;
public int length();
public boolean regionMatches(boolean ignoreCase, int toffset,String other, int ooffset, int len);
public boolean regionMatches(int toffset, String other,int ooffset, int len);
public String replace(char oldChar, char newChar);
public boolean startsWith(String prefix);
public boolean startsWith(String prefix, int toffset);
public String substring(int beginIndex);
public String substring(int beginIndex, int endIndex);
public char[] toCharArray();
public String toLowerCase();
public String toLowerCase(Locale locale);
public String toString();
public String toUpperCase();
public String toUpperCase(Locale locale); 
public String trim();
}

The details of the class structure are given as follows:

public String();
String myString=new String();

public String() constructor creates a new String object that represents the empty string (i.e., a string with zero characters).

 

 

public String(byte[] bytes); 

public String(byte[] bytes); constructor creates a new String object that represents the sequence of characters stored in the given bytes array.

The bytes in the array are converted to characters using the system’s default character encoding scheme.

Parameter
bytes – An array of byte values.

public String(byte[] bytes, String enc);

public String(byte[] bytes, String enc) constructor creates a new String object that represents the sequence of characters stored in the given bytes array.

The bytes in the array are converted to characters using the specified character encoding scheme.

Parameter
bytes – An array of byte values.
enc – The name of an encoding scheme.

public String(byte[] bytes, int offset, int length); 

public String(byte[] bytes, int offset, int length); constructor creates a new String object that represents the sequence of characters stored in the specified portion of the given bytes array.

The bytes in the array are converted to characters using the system’s default character
encoding scheme.

Parameter
bytes – An array of byte values.
offset – An offset into the array.
length – The number of bytes to be included.

public String(byte[] bytes, int offset,int length, String enc);

public String(byte[] bytes, int offset, int length, String enc) constructor creates a new String object that represents the sequence of characters stored in the specified portion of the given bytes array.

The bytes in the array are converted to characters using the specified character encoding scheme.

Parameter
bytes – An array of byte values.
offset – An offset into the array.
length – The number of bytes to be included.
enc – The name of an encoding scheme.

public String(byte[] lowbytes, int hibyte);

public String(byte[] lowbytes, int hibyte) constructor creates a new String object that represents the sequence of characters stored in the given lowbytes array.

The type of the array elements is a byte, which is an 8-bit data type, so each element must be converted to a char, which is a 16-bit data type. The value of the hibyte argument is used to provide the value of the high-order byte when the byte values in the array are converted to char values.

More specifically, for each element i in the array lowbytes, the character at position i in the created String object is:

((hibyte & 0xff)<<8) | lowbytes[i]

This method is deprecated because it does not convert bytes into characters properly. We should instead use one of the constructors that takes a specific character encoding argument or that uses the default encoding.

Parameter
lowbytes – An array of byte values.
hibyte – The value to be put in the high-order byte of each 16-bit character.

public String(byte[] lowbytes, int hibyte,int offset, int count);

public String(byte[] lowbytes, int hibyte, int offset, int count) constructor creates a new String object that represents the sequence of characters stored in the specified portion of the lowbytes array. That is, the portion of the array that starts at offset elements from the beginning of the array and is count elements long.

The type of the array elements is a byte, which is an 8-bit data type, so each element must be converted to a char, which is a 16-bit data type. The value of the hibyte argument is used to provide the value of the high-order byte when the byte values in the array are converted to char values.

More specifically, for each element, i in the array lowbytes that is included in the String object, the character at position i in the created String is:

((hibyte & 0xff)<<8) | lowbytes[I]

This method is deprecated because it does not convert bytes into characters properly. We should instead use one of the constructors that takes a specific character encoding argument or that uses the default encoding.

Parameter
lowbytes – An array of byte values.
hibyte – The value to be put in the high-order byte of each 16-bit character.
offset – An offset into the array.
count – The number of bytes from the array to be included in the string.

public String(char[] value);
char myChr[]={'x','y','z'};
String myStr=new String(myChr);

public String(char[] value) constructor creates a new String object that represents the sequence of characters stored in the given array.

Parameter
value – An array of char values.

public String(char[] value, int offset, int count);
char myChr[]={'x','y','z','a','b'};
String myStr=new String(myChr,1,2); //myStr holds "yz"

public String(char[] value, int offset, int count) constructor creates a new String object that represents the sequence of characters stored in the specified portion of the given array. That is, the portion of the given array that starts at offset elements from the beginning of the array and is count elements long.

Parameter
value – An array of char values.
offset – An offset into the array.
count – The number of characters from the array to be included in the string.

public String(String value);
String myStr=new String("Test")
String myStr2=new String(myStr);

public String(String value) constructor Creates a new String object that represents the same sequence of characters as the given String object.

In the above example myStr2 is actually a copy of myStr. However, both they point to different String objects.

Parameter
value – A String object.

public String(StringBuffer buffer);

public String(StringBuffer buffer) constructor creates a new String object that represents the same sequence of characters as the given object.

Parameter
value – A StringBuffer object.

public static String copyValueOf(char data[]);

public static String copyValueOf(char data[]) method returns a new String object that represents the character sequence contained in the given array.

The String object produced by this method is guaranteed not to refer to the given array, but instead to use a copy. Because the String object uses a copy of the array, subsequent changes to the array do not change the contents of this String object.

This method is now obsolete. The same result can be obtained using the valueOf() method that takes an array of char values.

This method returns a new String object that represents the sequence of characters stored in the given array.
Parameter
data – An array of char values.

public static String copyValueOf(char data[], int offset, int count);

public static String copyValueOf(char data[], int offset, int count) method returns a new String object that represents the character sequence contained in the specified portion of the given array. That is, the portion of the given array that starts at offset elements from the beginning of the array and is count elements long.

The String object produced by this method is guaranteed not to refer to the given array, but instead to use a copy. Because the String object uses a copy of the array, subsequent changes to the array do not change the contents of this String object.

This method is obsolete. The same result can be obtained by using the valueOf() method that takes an array of char values, an offset, and a count.

This method returns a new String object that represents the sequence of characters stored in the specified portion of the given array.

Parameter
data – An array of char values.
offset – An offset into the array.
count – The number of characters from the array to be included in the string.

public static String valueOf(boolean b);

public static String valueOf(boolean b) method returns a string representation of a boolean value. In other words, it returns ‘true’ if b is true or ‘false’ if b is false.

This method returns a new String object that contains ‘true’ if b is true or ‘false’ if b is false.

Parameter
b – A boolean value.

public static String valueOf(char c);

public static String valueOf(char c) method returns a string representation of a char value. In other words, it returns a String object that contains just the given character.

This method returns a new String object that contains just the given character.

Parameter
c – A char value.

public static String valueOf(char[] data);

public static String valueOf(char[] data) method returns a string representation of an array of char values. In other words, it returns a String object that contains the sequence of characters stored in the given array.

This method returns a new String object that contains the sequence of characters stored in the given array.

Parameter
data – An array of char values.

public static String valueOf(char[] data, int offset, int count);

public static String valueOf(char[] data, int offset, int count) method returns a string representation of the specified portion of an array of char values. In other words, it returns a String object that contains the sequence of characters in the given array that starts offset elements from the beginning of the array and is count elements long.

This method returns a new String object that contains the sequence of characters stored in the specified portion of the given array.

READ  Learn Java Step By Step Fast and Free

Parameter
data – An array of char values.
offset – An offset into the array.
count – The number of characters from the array to be included in the string.

public static String valueOf(double d);

public static String valueOf(double d) method returns a string representation of a double value. In other words, it returns the String object returned by Double.toString(d).

This method returns a new String object that contains a string representation of the given double value.

Parameter
d – A double value.

public static String valueOf(float f);

public static String valueOf(float f) method returns a string representation of a float value. In other words, it returns the String object returned by Float.toString(f).

This method returns a new String object that contains a string representation of the given float value.

Parameter
f – A float value.

public static String valueOf(int i);

public static String valueOf(int i) method returns a string representation of an int value. In other words, it returns the String object returned by Integer.toString(i).

This method returns a new String object that contains a string representation of the given int value.

Parameter
i – An int value.

public static String valueOf(long l);

public static String valueOf(long l) method returns a string representation of a long value. In other words, it returns the String object returned by Long.toString(l).

This method returns a new String object that contains a string representation of the given long value.

Parameter
l – A long value.

public static String valueOf(Object obj);

public static String valueOf(Object obj) method returns a string representation of the given object. If obj is null, the method returns’null’.

Otherwise, the method returns the String object returned by the toString() method of the object.

This method returns a new String that contains a string representation of the given object.

Parameter
obj – A reference to an object.

public char charAt(int index);

public char charAt(int index) method returns the character at the specified position in the String object; the first character in the string is at position 0.

This method returns the character at the specified position in this string.

Parameter
index – An index into the string.

public int compareTo(String anotherString);

public int compareTo(String anotherString) method lexicographically compares this String object to anotherString.

Here is how the comparison works: the two String objects are compared character-by-character, starting at index 0 and continuing until a position is found in which the two strings contain different characters or until all of the characters in the shorter string have been compared. If the characters at k are different, the method returns:

this.charAt(k)-anotherString.charAt(k)
Otherwise, the comparison is based on the lengths of the strings and the method returns:
this.length()-anotherString.length()

This method returns a positive value if this string is greater than anotherString, 0 if the two strings are the same, or a negative value if this string is less than anotherString.

Parameter
anotherString – The String object to be compared.

public String concat(String str);

public String concat(String str) method returns a new String object that concatenates the characters from the argument string str onto the characters from this String object. Although this is a good way to concatenate two strings, concatenating more than two strings can be done more efficiently using a StringBuffer object.

This method returns a new String object that contains the character sequences of this string and str concatenated together.

Parameter
str – The String object to be concatenated.

public boolean endsWith(String suffix);

public boolean endsWith(String suffix) method determines whether or not this String object ends with the specified suffix.

This method returns true if this string ends with the sequence of characters specified by suffix; otherwise false.

Parameter
suffix – The String object suffix to be tested.

public boolean equals(Object anObject);

public boolean equals(Object anObject) method returns true if anObject is an instance of String and it contains the same sequence of characters as this String object.

Note the difference between this method and the == operator, which only returns true if both of its arguments are references to the same object.

This method returns true if the objects are equal; false if they are not.

Parameter
anObject – The Object to be compared.

public boolean equalsIgnoreCase(String anotherString);

public boolean equalsIgnoreCase(String anotherString) method determines whether or not this String object contains the same sequence of characters, ignoring case, as anotherString. More specifically, corresponding characters in the two strings are considered equal if any of the following conditions are true:

  • The two characters compare as equal using the == operator.
  • The Character.toUppercase() method returns the same result for both characters.
  • The Character.toLowercase() method returns the same result for both characters.

This method returns true if the strings are equal, ignoring case; otherwise false

Parameter
anotherString – The String object to be compared.

public byte[] getBytes(); 

public byte[] getBytes(); method converts the characters in this String object to an array of byte values. The characters in the string are converted to bytes using the system’s default character encoding scheme.

This method returns a byte array that contains the characters of this String.

public byte[] getBytes(String enc); 

public byte[] getBytes(String enc); method converts the characters in this String object to an array of byte values. The characters in the string are converted to bytes using the specified character encoding scheme.

This method returns a byte array that contains the characters of this String.

Parameter
enc – The name of an encoding scheme.

public void getBytes(int srcBegin, int srcEnd,byte[] dst, int dstBegin); 

public void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin); method copies the low-order byte of each character in the specified range of this String object to the given array of byte values. More specifically, the first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1. The low-order bytes of these characters are copied into dst, starting at index dstBegin and ending at index:

dstBegin + (srcEnd-srcBegin) – 1

This method is deprecated because it does not convert characters into bytes properly. We should instead use the getBytes() method that takes a specific character encoding argument or the one that uses the default encoding.

Parameter
srcBegin – The index of the first character to be copied.
srcEnd – The index after the last character to be copied.
dst – The destination byte array.
dstBegin – An offset into the destination array.

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

public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method copies each character in the specified range of this String object to the given array of char values. More specifically, the first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1. These characters are copied into dst, starting at index dstBegin and ending at index:

dstBegin + (srcEnd-srcBegin) – 1

Parameter
srcBegin – The index of the first character to be copied.
srcEnd – The index after the last character to be copied.
dst – The destination char array.
dstBegin – An offset into the destination array.

public int hashCode();

public int hashCode() method returns a hashcode based on the sequence of characters this String object represents.

More specifically, one of two algorithms is used to compute a hash code for the string, depending on its length.

This method returns a hashcode based on the sequence of characters in this string.

public int indexOf(int ch);

public int indexOf(int ch) method returns the index of the first occurrence of the given character in this String object. If there is no such occurrence, the method returns the value -1.

This method returns the index of the first occurrence of the given character in this string or -1 if the character does not occur.

Parameter
ch – A char value.

public int indexOf(int ch, int fromIndex);

public int indexOf(int ch, int fromIndex) method returns the index of the first occurrence of the given character in this String object after ignoring the first fromIndex characters. If there is no such occurrence, the method returns the value -1.

This method returns the index of the first occurrence of the given character in this string after fromIndex or -1 if the character does not occur.

Parameter
ch – A char value.
fromIndex – The index where the search is to begin.

public int indexOf(String str);

public int indexOf(String str) method returns the index of the first character of the first occurrence of the substring str in this String object. If there is no such occurrence, the method returns the value -1.

This method returns the index of the first occurrence of str in this string or -1 if the substring does not occur.

Parameter
str – A String object.

public int indexOf(String str, int fromIndex);

public int indexOf(String str, int fromIndex) method returns the index of the first character of the first occurrence of the substring str in this String object after ignoring the first fromIndex characters. If there is no such occurrence, the method returns the value -1.

This method returns the index of the first occurrence of str in this string after fromIndex or -1 if the substring does not occur.

Parameter
str – A String object.
fromIndex – The index where the search is to begin.

public native String intern();

public native String intern() method returns a canonical representation for this String object. The returned String object is guaranteed to be the same String object for every String object that contains the same character sequence. In other words, if:

s1.equals(s2)

then:
s1.intern() == s2.intern()

The intern() method is used by the Java environment to ensure that String literals and constant-value String expressions that contain the same sequence of characters are all represented by a single String object.

This method returns a String object that is guaranteed to be the same object for every String that contains the same character sequence.

public int lastIndexOf(int ch);

public int lastIndexOf(int ch) method returns the index of the last occurrence of the given character in this String object. If there is no such occurrence, the method returns the value -1.

This method returns the index of the last occurrence of the given character in this string or -1 if the character does not occur.

Parameter
ch – A char value.

public int lastIndexOf(int ch, int fromIndex);

public int lastIndexOf(int ch, int fromIndex) method returns the index of the last occurrence of the given character in this String object after ignoring the first fromIndex characters. If there is no such occurrence, the method returns the value -1.

This method returns the index of the last occurrence of the given character in this string after fromIndex or -1 if the character does not occur.

Parameter
ch – A char value.
fromIndex – The index where the search is to begin.

public int lastIndexOf(String str);

public int lastIndexOf(String str) method returns the index of the first character of the last occurrence of the substring str in this String object. If there is no such occurrence, the method returns the value -1.

This method returns the index of the last occurrence of str in this string or -1 if the substring does not occur.

Parameter
str – A String object.

public int lastIndexOf(String str, int fromIndex);

public int lastIndexOf(String str, int fromIndex) method returns the index of the first character of the last occurrence of the substring str in this String object after ignoring the first fromIndex characters. If there is no such occurrence, the method returns the value -1.

This method returns the index of the last occurrence of str in this string after fromIndex or -1 if the substring does not occur.

Parameter
str – A String object.
fromIndex – The index where the search is to begin.

public int length();

public int length() method returns the number of characters in the character sequence represented by this String object.

This method returns the length of the character sequence represented by this string.

public boolean regionMatches(boolean ignoreCase, int toffset,String other, int ooffset, int len);

public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) method determines whether or not the specified sub-sequences in this String object and other are identical. The method returns false if toffset is negative, if the ooffset is negative, if toffset+len is greater than the length of this string, or if ooffset+len is greater than the length of the other. Otherwise, the method returns true if for all nonnegative integers k less than len it is true that:

this.charAt(toffset+k) == other.charAt(ooffset+k)

This method returns true if the sub-sequences are identical; otherwise false.

Parameter
toffset – The index of the first character in this string.
other – The String object to be used in the comparison.
ooffset – The index of the first character in other.
len – The length of the sub-sequences to be compared.

public boolean regionMatches(int toffset, String other,int ooffset, int len);

public boolean regionMatches(int toffset, String other,int ooffset, int len) method determines whether or not the specified sub-sequences in this String object and other are identical. The method returns false if toffset is negative, if ooffset is negative, if toffset+len is greater than the length of this string, or if ooffset+len is greater than the length of other. Otherwise, if ignoreCase is false, the method returns true if for all nonnegative integers k less than len it is true that:

READ  PrintWriter Class in Java

this.charAt(toffset+k) == other.charAt(ooffset+k)

If ignoreCase is true, the method returns true if for all nonnegative integers k less than len it is true that:

Character.toLowerCase(this.charAt(toffset+k))== Character.toLowerCase(other.charAt(ooffset+k))

or:
Character.toUpperCase(this.charAt(toffset+k))== Character.toUpperCase(other.charAt(ooffset+k))

This method returns true if the sub-sequences are identical; otherwise false. The ignoreCase argument controls whether or not the case is ignored in the comparison.

Parameter
ignoreCase – A boolean value that indicates whether a case should be ignored.
toffset – The index of the first character in this string.
other – The String object to be used in the comparison.
ooffset – The index of the first character in other.
len – The length of the sub-sequences to be compared.

public String replace(char oldChar, char newChar);

public String replace(char oldChar, char newChar) method returns a new String object that results from replacing every occurrence of oldChar in this String object with newChar. If there are no occurrences of oldChar, the method simply returns this String object.

This method returns a new String object that results from replacing every occurrence of oldChar in the string with newChar.

Parameter
oldChar – The character to be replaced.
newChar – The replacement character.

public boolean startsWith(String prefix);

public boolean startsWith(String prefix) method determines whether or not this String object begins with the specified prefix.

This method returns true if this string begins with the sequence of characters specified by prefix; otherwise false.

Parameter
prefix -The String object prefix to be tested.

public boolean startsWith(String prefix, int toffset);

public boolean startsWith(String prefix, int toffset) method determines whether or not this String object contains the specified prefix at the index specified by toffset.

This method returns true if this string contains the sequence of characters specified by prefix starting at the index toffset; otherwise false.

Parameter
prefix – The String object prefix to be tested.
toffset – The index where the search is to begin.

public String substring(int beginIndex);

public String substring(int beginIndex) method returns a new String object that represents a sub-sequence of this String object. The sub-sequence consists of the characters starting at beginIndex and extending through the end of this String object.

This method returns a new String object that contains the sub-sequence of this string that starts at beginIndex and extends to the end of the string.

Parameter
beginIndex – The index of the first character in the substring.

public String substring(int beginIndex, int endIndex);

public String substring(int beginIndex, int endIndex) method returns a new String object that represents a sub-sequence of this String object. The sub-sequence consists of the characters starting at beginIndex and extending through endIndex-1 of this String object.

This method returns a new String object that contains the sub-sequence of this string that starts at beginIndex and extends to the character at endindex-1.

Parameter
beginIndex – The index of the first character in the substring.
endIndex – The index after the last character in the substring.

public char[] toCharArray();

public char[] toCharArray() method returns a new char array that contains the same sequence of characters as this String object. The length of the array is the same as the length of this String object.

This method returns a new char array that contains the same sequence of characters as this string.

public String toLowerCase();

public String toLowerCase() method returns a new String that represents a character sequence of the same length as this String object, but with each character replaced by its lowercase equivalent if it has one. If no character in the string has a lowercase equivalent, the method returns this String object.

This method returns a new String object that contains the characters of this string converted to lowercase.

public String toLowerCase(Locale locale);

public String toLowerCase(Locale locale) method returns a new String that represents a character sequence of the same length as this String object, but with each character replaced by its lowercase equivalent if it has one according to the rules of the specified locale. If no character in the string has a lowercase equivalent, the method returns this String object.

This method returns a new String object that contains the characters of this string converted to lowercase using the rules of the specified locale.

Parameter
locale -The locale to use.

public String toString();

public String toString() method returns this String object.

This method returns this String object.

public String toUpperCase();

public String toUpperCase() method returns a new String that represents a character sequence of the same length as this String object, but with each character replaced by its uppercase equivalent if it has one. If no character in the string has an uppercase equivalent, the method returns this String object.

This method returns a new String object that contains the characters of this string converted to uppercase.

public String toUpperCase(Locale locale); 

public String toUpperCase(Locale locale); method returns a new String that represents a character sequence of the same length as this String object, but with each character replaced by its uppercase equivalent if it has one according to the rules of the specified locale. If no character in the string has an uppercase equivalent, the method returns this String object.

This method returns a new String object that contains the characters of this string converted to uppercase using the rules of the specified locale.

Parameter
locale – The locale to use.

public String trim();

public String trim() method returns this String object If the first and last character in this String object is greater than ‘\u0020’ (the space character). Otherwise, the method returns a new String object that contains the same character sequence as this String object, but with leading and trailing characters that are less than ‘\u0020” removed.

This method returns a new String object that represents the same character sequence as this string, but with leading and trailing whitespace and control characters removed.

Apart from these String class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

String Creation techniques

Create String from an Array of Characters

java String is an array of characters. But showing String as an array of characters is very troublesome and tedious to code. String falls under java.lang.String class hierarchy. The import is automatic hence we do not need to import it manually. A String is an Object. The object contains data(a sequence of characters)

An example is given below:

char[] myString={'I','N','D','I','A'};
String myFinalString=new String(myString);
 

Java has come up with an important class called String to omit this issue.

Direct String creation

String myFinalString="INDIA"; 

To create a String assign a double-quoted constant to a string variable. Java automatically converts the string literals into a String object.

The String class actually uses a java character array. It is private to String class, so we can not get the characters and change them.

Arrays in Java are real objects that knows its own length, so String objects do not need a special terminator.

Create String using Array and encoding scheme

byte[] data={65,66,67};
String myString=new String(data,"8859_5");
The arguments are:
byte array
encoding scheme 

If we do not wish to provide an encoding scheme, we can pass only the byte array.A default encoding scheme will be used in that case.

Create Strings from other data types

There are several data types that can be converted to String. There are various overloaded versions of String.valueOf() methods available.

Example:

String myString=String.valueOf(1);//int to String
String myString=String.valueOf(2.0f);//float to String
String myString=String.valueOf(false);//boolean to String

Converting Objects to String:

toString() is a method to convert objects into String. If the object is null, the equivalent string output will be null.

Concatenation:

Java String supports the concatenation for two different strings. This operation is done with a “+” operator. This + is an overloaded operator and signifies to concatenate in the context of String. + is known as a concatenation operator in java.


public class StringTest{
public static void main(String[] args)
{
String first="Hello";
String second="World";
String finalString=first+second;
System.out.println(finalString);
}
}

The output of the code is :
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
HelloWorld

In case, if we need to concatenate String and any other type, the other type is converted to String first and then concatenated with String.

String abc="Hello"
abc=abc+12

The output will be – Hello12

Literal strings can not span across lines in java. But we can concatenate lines to produce the same result.

String myString="Hello".concat(" java");

Few important methods to remember about String Class:

NoMethod NameMethod DescriptionReturnComment
1int length()Returns the length of the String Objectint
2int indexOf(‘character’)Returns the index of the given character for the calling String Object.int indexIf the character is inside the String it will return the first occurrence, if the character is not inside of the given string, it will return -1
3char chatAt(index)Returns the character present at the given index for the calling String Object.charif the index is inside the bound, it will return the character but if the index is outside of the Bound, it will throw a StringIndexOutOfBoundsException
4boolean contains(“Char sequence”)Returns true if the character or character sequence or String is present inside the given string, else it will return falseboolean true or falsein case we test if the String contains null, it will return null pointer Exception
5boolean endsWith(‘Character’)Returns true if the given string ends with the specified character else return falseboolean true or false
6String replaceAll(“search String”,”replace String”)Returns the changed String if a valid replacement found else returns the original stringStringThe changed output does not get assigned to the variable automatically, we need to assign them
7String replaceFirst(“search String”,”replace String”)Returns the changed String if a valid replacement found for the first occurrence else returns the original stringStringThe changed output does not get assigned to the variable automatically, we need to assign them
8String toLowerCase(“String whose case needs to be changed”)Returns the lowercase representation for the calling String Object.StringThe changed output does not get assigned to the variable automatically, we need to assign them
9String toUpperCase(“String whose case needs to be changed”)Returns the uppercase representation for the calling String Object.StringThe changed output does not get assigned to the variable automatically, we need to assign them
10int indexOf(Char c,int StartIndex)Returns the index of the character specified after the index specified instead of searching from the beginning if no match found it will return -1intOverloaded version of indexOf() method
11int indexOf(String subString)Returns the index of the subString specified from the beginning if no match found it will return -1intOverloaded version of indexOf() method
12int indexOf(String subString,int startIndex)Returns the index of the subString specified after the index specified instead of searching from the beginning if no match found it will return -1intOverloaded version of indexOf() method
13int compareTo(String string1,String string2)lexicographically compares two strings and based on the comparison, it may return 0, negative value or a positive valueint0 means it is an exact match, positive means the first string is lexicographically ahead of the second string and a negative means the first string is lexicographically behind.
14String concate(String string1)it will concatenate the given string with another stringString
14boolean equals(String string1)Returns true if the calling object string and string1 are equal else return false.boolean

Example of each function is given below:


public class StringTest{
public static void main(String[] args)    
{
//Declare and define a String    
String first="INDIA";
String second="INDIAINDIA";
String third="abc";
//get the lenth of the String
System.out.println("The size is"+first.length());
//get the index of the given valid character
System.out.println("The index of D is "+first.indexOf('D'));
//get the index of the given invalid character
System.out.println("The index of E is "+first.indexOf('E'));
//get the character at a given index-index starts at 0
System.out.println("The Character at 2 is "+first.charAt(2));
//check contain() method for "IA"
boolean flag1=first.contains("IA");
System.out.println("The Character sequence IA is present in the string "+flag1);
//check contain() method for "DA" i.e invalid character sequence
boolean flag2=first.contains("DA");
System.out.println("The Character sequence DA is present in the string "+flag2);
//Check the end with function with valid character
boolean flag3=first.endsWith("A");
System.out.println("The string does ends with A "+flag3);
//Check the end with function with invalid character
boolean flag4=first.endsWith("I");
System.out.println("The string does ends with I "+flag4);
//replceAll() valid test
System.out.println("Testing replace All with IN with in "+second+" becomes "+second.replaceAll("IN","in"));
//replceAll() invalid test
System.out.println("Testing replace All with IN with in "+second+" becomes "+second.replaceAll("TA","in"));
//replceFirst() valid test
System.out.println("Testing replace First with IN with in "+second+" becomes "+second.replaceFirst("IN","in"));
//replceAll() invalid test
System.out.println("Testing replace All with IN with in "+second+" becomes "+second.replaceFirst("TA","in"));
//test tolowercase
System.out.println("Testing toLowercase method "+second+" becomes "+second.toLowerCase());
//test toUpperCase
System.out.println("Testing toUpperCase method "+third+" becomes "+third.toUpperCase());

}
}

The output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
The size is5
The index of D is 2
The index of E is -1
The Character at 2 is D
The Character sequence IA is present in the string true
The Character sequence DA is present in the string false
The string does end with A true
The string does end with I false
Testing replace All with IN with in INDIAINDIA becomes inDIAinDIA
Testing replace All with IN with in INDIAINDIA becomes INDIAINDIA
Testing replace First with IN with in INDIAINDIA becomes inDIAINDIA
Testing replace All with IN with in INDIAINDIA becomes INDIAINDIA
Testing toLowercase method INDIAINDIA becomes indiaindia
Testing the toUpperCase method abc becomes ABC

READ  How to Work with AudioClip in Java?

Overloaded functions of indexOf() methods:


public class StringTest{
public static void main(String[] args)    
{
String a="10abd10ab";
//test of indexOf(char,startindex) for a valid test
System.out.println("The index of second a character "+a.indexOf('a',3));
//test of indexOf(char,startindex) for a invalid test
System.out.println("The index of second e character "+a.indexOf('e',3));
//test of indexOf(subString) for a valid test
System.out.println("The index of subString "+a.indexOf("ab"));
//test of indexOf(subString) for a valid intest
System.out.println("The index of subString "+a.indexOf("abc"));
//test of indexOf(subString,startIndex) for a valid test
System.out.println("The index of subString "+a.indexOf("ab",3));
//test of indexOf(subString,startIndex) for a valid intest
System.out.println("The index of subString "+a.indexOf("abc",3));
}
}

the output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
The index of second a character 7
The index of seconde character -1
The index of subString 2
The index of subString -1
The index of subString 7
The index of subString -1
The string is a final class i.e once created they can not be altered or deleted. There handle gets changed. So while overriding a String. A new String object gets created, the pointer or handles the new object. This is why String is called an immutable class. JVM creates a memory in the String Constant Pool. This is also the reason why String can be initiated without a new operator.


public class StringTest{
public static void main(String[] args)    
{
String a="India";
a="India"+"n";
System.out.println(a);
}
}

the output of the program:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
Indian

In this case, a becomes “Indian”, but the String “India” still remains in the String pool,(does not get deleted). It just loses the handle.
Similarly for multiple occurrences of the same String will not create multiple Strings in the pool. It is just one String gets created and the variables hold the reference of that String.


String a="India";
String b="India";
String c="India";

Here a,b,c three variable points to the same String in the pool.
If a number is quoted with a double-quote, it becomes a string not a number anymore.


public class StringTest{
public static void main(String[] args)    
{
String a="10";
System.out.println("value of a"+a);
System.out.println("Trying to add 2 with a"+a+2);
}
}

the output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
value of a10
Trying to add 2 with a102
In this case, a represents 10 as a string when it gets 2 that is of numeric, the autoboxing features get activated then converted to an Object type as new Integer(2). Second, the + operator is an overloaded operator that represents concatenation. The Object, new Integer(2) gets converted to String using the toString() method. Last- the compiler concatenates two strings. Hence we get 102 as output.

The next question is how to get is as numeric?

Well for that we have String parsing methods:


public class StringTest{
public static void main(String[] args)    
{
String a="10";
int b=Integer.parseInt(a);
System.out.println("Numberic value of a "+a);
System.out.println("add 2 with b gives "+(b+2));
}
}

output of this code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
Numberic value of a 10
add 2 with b gives 12
If the String represents combination of String and number or two primitive values. The parsing will not happen.Instead JVM will throw an exception called java.lang.NumberFormatException.


public class StringTest{
public static void main(String[] args)    
{
String a="10abd";
int b=Integer.parseInt(a);
System.out.println("Numberic value of a "+a);
System.out.println("add 2 with b gives "+(b+2));
}
}

The output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
Exception in thread “main” java.lang.NumberFormatException: For input string: “10abd”
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at StringTest.main(StringTest.java:5)

Why String class is not like other classes in java

In Java, You can create a String object as:

String str = “abc”; &  String str = new String(“abc”);

Why cant a button object be created as :

Button bt = “abc”

Why is it compulsory to create a button object as:

Button bt = new Button(“abc”);

Why is this not compulsory in String’s case?

Well, This is a question that is asked almost in every forum. The answered solutions are good for the interview. Like String is an immutable class so this type of assignment is possible
String str = “abc”; &  String str = new String(“abc”);

But here let us look at the internal logic why Java is giving such flexibility to the user. How this is beneficial for us.
Java is a language wherefrom the client-side window, client-side page to server-side caching, database query to item display, Even for simple data display ..everywhere, there is a string. The string is used extensively.
Now if we use so much of String in our program we need to think the memory allocation for the same.
minimum memory usage of a Java String::
Minimum String memory usage (bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)
so for a null string, the required memory will be =8*5=40 byte!!!!!!!!!!!!!!!
Now think about your page or GUI …how many Strings (objects) are there.
every object has at least 8 bytes of housekeeping data, and arrays 12 bytes, and will be padded to a multiple of 16 bytes (in 32-bit versions of Hotspot);

  • a Java String actually consists of more than one object;
  • a Java char takes up two bytes, even if you’re using them to store boring old ASCII values that would fit into a single byte;
  • a Java String contains some extra variables that you might not have considered.

So if java would have given that facility for the string in java then it would have a real memory problem for all of us. Again so much of the object needs to be handled.

They made our life easy…How to let’s see…..

They introduced two ways while working with String

    • String pool
    • String Object

How do they work—

A JVM has the Pool. All the String Object which are created by assignment stored in the pool. This pool is present in the heap. So whenever any assignment is done for String first it checks in the String Pool whether that String already exists or not… This is done by calling the intern() method present in the String class. If it finds the same String then it returns the same reference else it creates a new one. But with the new Operator every time it creates the new Object.

Important to note that you are NOT calling a java.lang.String constructor when you type

String s =
"xyz"; for example:
String x = "xyz";
String y = "xyz";

refer to the same object in the pool.
While

String x1 = new String ("xyz");
String x2 = new String ("xyz");

refer to two different objects.
By this mechanism, Java is saving memory. Hence your application performance is becoming good. But how many buttons will be there on a page?? Will they be so many as String?????
Hence java has given it for string, not for a button.

Immutability

An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object.

The popular immutable classes are

Immutable classes are-

  • Easy to design
  • Easy to use
  • Very much secure
  • Easy to implement
  • Less error-prone

To make immutable just like String we need to follow the followings:

  1. Do not provide any methods that modify the object(otherwise known as mutators)
  2. Ensure no methods can be overridden. This helps subclasses from compromising the immutable behavior of the class. (The popular way to make the class final)
  3. Make all fields final.

String Comparison In Java

NoMethod NameMethod DescriptionReturnComment
1compareToCompares one string with other<0 if the String which is calling this method is lexicographically first(comes first in the dictionary)</br>
=0 if the Strings are same</br>
>0 if the parameter passed is lexicographically first(comes first in the dictionary)
This method is case sensitive
2compareToIgnoreCaseCompares one string with other<0 if the String which is calling this method is lexicographically first(comes first in the dictionary)</br>
=0 if the Strings are same</br>
>0 if the parameter passed is lexicographically first(comes first in the dictionary)
This method is case insensitive

public class StringTest{
public static void main(String[] args)    
{
String a="India";
String b="India";
String c="Indian";
String d="Bangladesh";
String e="Vietnam";
String f="india";
System.out.println("When both are same, it generates "+ a.compareTo(b));
System.out.println("When both are not same, it generates "+ a.compareTo(c));
//lexicographically Bangladesh is ahead of India
System.out.println("When both are not same, it generates "+ a.compareTo(d));
//lexicographically India is ahead of vietnam
System.out.println("When both are not same, it generates "+ a.compareTo(e));
//test of ignorecase
System.out.println("When both are not same case wise, it generates "+ a.compareToIgnoreCase(f));
}
}

The output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
When both are same, it generates 0
When both are not same, it generates -1
When both are not same, it generates 7
When both are not same, it generates -13
When both are not same case wise, it generates 0

The second set of String comparison methods: equals() and equalsIgnoreCase(). Both the methods have overridden a method from class Object and compare character by character for the given two strings.

NoMethod NameMethod DescriptionReturnComment
1equals()Checks if the two strings are equalboolean true or false
2equalsIgnoreCase()Checks if the two strings are equal ignoring the caseboolean true or false

public class StringTest{
public static void main(String[] args)
{
String a="India";
String b="India";
String d="Indian";
String c=new String("India");
System.out.println("Checking equals with two same string gives "+a.equals(b));
System.out.println("Checking equals with two same string gives "+a.equals(d));
System.out.println("Checking equals with two same string gives "+a.equals(c));
}
}

the output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
Checking equals with two same string gives true
Checking equals with two same string gives false
Checking equals with two same string gives true

The third method of comparing String is “==” operator. In Object class there is also a method calls equals() which checks the addresses instead of content. So if both strings point to the String in String pool, or if both they are null, they will return true. Else JVM will call equals() method of String class and they will return false.


public class StringTest{
public static void main(String[] args)   
{
String a="India";
String b="India";
String c=new String("India");
System.out.println("When both are same, it generates "+ (a==b));
System.out.println("When both are same, it generates "+ (a==c));
}
}

The output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
When both are same, it generates true
When both are same, it generates false

 

Why we should not use == to compare a String?
Java has two types of storage for storing variable-Heap and Stack. While working with primitive data types, when we create variables of the primitive type it is stored in stack for quick access.
When we create an object that is String, it goes to the heap. The address of the heap is given to the object(variable) stored to stack.It
So when == is applied to primitives to compare then it is ok. For objects(String), it is not applicable. It only checks if both the variable holds the same address. Otherwise, it will always return falls. “==” operator check on the stack not on the heap.
you can refer to this link for all the documentation
So == checks for reference equality and equals() method check for content.
The explanation is given here also:
Author Credit: Ganesh
Johannes H


String a="Test";
String b="Test";
if(a==b) ===> true
 

This is because when you create any String literal, the JVM first searches for that literal in the String pool, and if it finds a match, that same reference will be given to the new String. Because of this, we get:


(a==b) ===> true
 

String Pool
b —————–> “test” <—————–a
However, == fails in the following case:


String a="test";
String b=new String("test");
if (a==b) ===> false
 

In this case for new String(“test”) the statement new String will be created on the heap, and that reference will be given to b, so b will be given a reference on the heap, not in String pool.

Now a is pointing to a String in the String pool while b is pointing to a string on the heap. Because of that, we get:

if(a==b) ===> false.

String Pool
“test” <——————– a

Heap
“test” <——————– b
While .equals() always compares a value of String so it gives true in both cases:


String a="Test";
String b="Test";
if(a.equals(b)) ===> true
String a="test";
String b=new String("test");
if(a.equals(b)) ===> true

The last section of String comparison with Apache common Library: Apache provides a special called Utility that has the below methods for String comparison. It is a little advanced version of the String class’s comparison method. They are null safe.
The methods are:

  • equals() and equalsIgnoreCase() ==>Same as String’s equal() and equalsIgnoreCase()
  • equalsAny() and equalsAnyIgnoreCase()==> This is applicable for multiarg Scenarios. Returns true if both the values are same.
  • compare() and compareIgnoreCase()=>Null safe, hence two nulls are considered as true if compared.

Why Java’s inbuilt toString() is not very efficient for human consumption?

While concatenating java converts the data into the equivalent String using the valueOf() function. This function is defined in String class. valueOf() method provides a human consumable format of the data. But if we use toString() method, this approach is not that effective.

However, toString() function is defined in Object class which is a the base class of all the classes. toString() method returns the wired @ symbol in the output. That is not consumable by the human.

package javaPractice;

public class TestClass {
private int a,b;
TestClass(){
	a=b=0;
}
TestClass(int x,int y){
	a=x;
	b=y;
}

}

The actual test class looks like:


package javaPractice;

public class MyToStringTest {

	public static void main(String[] args) {
		TestClass tc=new TestClass(1,2);
		System.out.println(tc);
		String newStr="The value of the object"+tc;
		System.out.println(newStr);

	}

}

The output will be as follows:
[email protected]
The value of the [email protected]
In order to rectify this, we can override the toString() method:

package javaPractice;

public class TestClass {
private int a,b;
TestClass(){
	a=b=0;
}
TestClass(int x,int y){
	a=x;
	b=y;
}
public String toString()
{
	return (a+","+b);
}

}

Now the output is :
1,2
The value of the object1,2

This is why overriding the toString() method is must.

Share and Enjoy !

24 thoughts on “Learn String Class in Java Quick in 20 Minutes”

  1. You actually make it appear really easy with your presentation however
    I in finding this matter to be really something which I believe I would never understand.
    It sort of feels too complex and very vast for me. I’m taking a look forward on your next
    submit, I’ll attempt to get the cling of it!

  2. Does your site have a contact page? I’m having problems locating it but, I’d like to shoot you an email.
    I’ve got some suggestions for your blog you might be interested in hearing.
    Either way, great site and I look forward to seeing it expand over time.

  3. Its not my first time to pay a visit this web site,
    i am visiting this site dailly and get pleasant facts from here
    daily.

  4. Hi there all, here every person is sharing such experience, thus it’s good to
    read this blog, and I used to pay a quick visit this blog
    every day.

  5. Pingback: Google

  6. Generally I usually do not learn post on blogs, but I would like to claim that this
    write-up very compelled me to have a look at and do
    it! Your writing taste has become surprised me. Thank you, very nice article.

  7. Having read this I believed it absolutely was really enlightening.
    I appreciate you making the effort and effort to
    put this informative article together. One time i again find myself spending
    a significant amount of time both reading and leaving comments.
    But so what, it was still worthwhile!

  8. Pingback: Google

  9. Pingback: Google

  10. Everything is very open with a precise description of the challenges.
    It had been truly informative. Your internet site is
    very beneficial. I appreciate you sharing!

  11. hulda.fairweather

    You can certainly see your enthusiasm in the work you
    write. The arena hopes for even more passionate writers like
    you who aren’t afraid to mention how they believe.
    At all times follow your heart.

  12. What you posted was actually very reasonable.
    However, what about this? what if you wrote a catchier post title?
    I mean, I don’t wish to tell you how to run your website, but what if
    you added something to possibly get people’s
    attention? I mean Learn String Class In Java Quick In 20 Minutes – Tech Travel Hub is kinda boring.
    You ought to peek at Yahoo’s front page and watch how they write article
    titles to grab people to click. You might add a video
    or a picture or two to get people excited about everything’ve got
    to say. In my opinion, it could make your website a little bit more interesting.

  13. florentinamonzon

    It’s an remarkable piece of writing for all the internet viewers; they will obtain benefit from it
    I am sure. adreamoftrains best web hosting

  14. Pingback: Google

  15. Pingback: Google

  16. Pingback: Google

  17. Pingback: Google

  18. Pingback: Google

  19. Pingback: Google

  20. Pingback: Google

  21. Pingback: Google

  22. Cool blog! Is your theme tailor made or do you download it from somewhere?
    A design like yours with some simple tweeks would
    really make my blog jump out. Please let me know that you
    got your theme. Many thanks

Leave a Comment

Your email address will not be published. Required fields are marked *