String in Java

Rumman Ansari   Software Engineer   2019-03-30   8761 Share
☰ Table of Contents

Table of Content:


String is the most commonly used class in java library. String class is encapsulated under java.lang package. 

The Java platform provides the String class to create and manipulate strings.

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. i.e 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.

An array of characters works same as java string. For example:

 char[] ch={'H','e','l','l','o','W','o','r','l','d'};  
String s=new String(ch);  
is same as:
String s="HelloWorld";  

What is an Immutable object?

An object whose state cannot be changed after it is created is known as an Immutable object. String, Integer, Byte, Short, Float, Double and all other wrapper classes objects are immutable.


Creating an Immutable class

 

public final class MyString
{
 final String str;
 MyString(String s)
 {
  this.str = s;
 }
 public String get()
 {
  return str;
 }
}

In this example MyString is an immutable class. MyString's state cannot be changed once it is created.

How to create String object?

There are two ways to create String object:

  1. By string literal
  2. Using another String object
  3. By new keyword

1) String Literal

The most direct way to create a string is to write:

String strng = "Hello world!";

In this case, "Hello world!" is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world!.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println(helloString);

The last line of this code snippet displays hello.


Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

Note: String objects are stored in a special memory area known as string constant pool.

2) Using another String object

 String str2 = new String(str1);
 

2) Using new Keyword

 String s1=new String("HelloWorld");
 //creates two objects and one reference variable  

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Java String Example

Program

  public class SampleString{
public static void main(String args[]){

	String s1="Hello";//creating string by java string literal

	char character[]={'a','t','n','y','l','a'};

	String s2=new String(character);//converting char array to string
	String s3=new String("welcome");//creating java string by new keyword

	System.out.println(s1);
	System.out.println(s2);
	System.out.println(s3);
	}
}
  

Program

  Hello
atnyla
welcome
Press any key to continue . . .
  

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17:

String palindrome = "Dot saw I was Tod";
int len = palindrome.length();

The following program is an example of length(), method String class.

Program

public class SampleString {

   public static void main(String args[]) {
      String strng = "Man can't do everything";
      int len = strng.length();
      System.out.println( "String Length is : " + len );
   }
}
  

Program

String Length is : 23
Press any key to continue . . .
  

palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes the String method charAt(i), which returns the ith character in the string, counting from 0.

public class StringDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
        
        // put original string in an 
        // array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = 
                palindrome.charAt(i);
        } 
        
        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }
        
        String reversePalindrome =
            new String(charArray);
        System.out.println(reversePalindrome);
    }
}

Running the program produces this output:

doT saw I was toD

To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string. The String class includes a method, getChars(), to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above with

palindrome.getChars(0, len, tempCharArray, 0);

Concatenating Strings

The String class includes a method for concatenating two strings:

string1.concat(string2); 

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

"My name is ".concat("ILoveYou");

Strings are more commonly concatenated with the + operator, as in

"World," + " Brotherhood" + "!"

which results in

"World, Brotherhoood!"

The + operator is widely used in print statements. For example:

String string1 = "you are man";
System.out.println("I," + string1 + " wow!");

which prints

I,you are man wow!

Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.


Note: The Java programming language does not permit literal strings to span lines in source files, so you must use the + concatenation operator at the end of each line in a multi-line string. For example:
String quote = 
    "Now is the time for all good " +
    "men to come to the aid of their country.";

Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.

Example of Concatenating Strings

public class SampleString {

   public static void main(String args[]) {
      String string1 = "I Hate You";
      System.out.println("Hey, " + string1 + "Girls");
   }
}
  

Program

Hey, I Hate YouGirls
Press any key to continue . . .
  

Creating Format Strings

You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a Stringobject rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of

System.out.printf("The value of the float " +
                  "variable is %f, while " +
                  "the value of the " + 
                  "integer variable is %d, " +
                  "and the string is %s", 
                  floatVar, intVar, stringVar); 

you can write

String fs;
fs = String.format("The value of the float " +
                   "variable is %f, while " +
                   "the value of the " + 
                   "integer variable is %d, " +
                   " and the string is %s",
                   floatVar, intVar, stringVar);
System.out.println(fs);

String Methods

Here is the list of methods supported by String class ?

Sr.No. Method & Description
1 char charAt(int index)

Returns the character at the specified index.

2 int compareTo(Object o)

Compares this String to another Object.

3 int compareTo(String anotherString)

Compares two strings lexicographically.

4 int compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences.

5 String concat(String str)

Concatenates the specified string to the end of this string.

6 boolean contentEquals(StringBuffer sb)

Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.

7 static String copyValueOf(char[] data)

Returns a String that represents the character sequence in the array specified.

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

Returns a String that represents the character sequence in the array specified.

9 boolean endsWith(String suffix)

Tests if this string ends with the specified suffix.

10 boolean equals(Object anObject)

Compares this string to the specified object.

11 boolean equalsIgnoreCase(String anotherString)

Compares this String to another String, ignoring case considerations.

12 byte getBytes()

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

13 byte[] getBytes(String charsetName)

Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

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

Copies characters from this string into the destination character array.

15 int hashCode()

Returns a hash code for this string.

16 int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character.

17 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.

18 int indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.

19 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.

20 String intern()

Returns a canonical representation for the string object.

21 int lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified character.

22 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.

23 int lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the specified substring.

24 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.

25 int length()

Returns the length of this string.

26 boolean matches(String regex)

Tells whether or not this string matches the given regular expression.

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

Tests if two string regions are equal.

28 boolean regionMatches(int toffset, String other, int ooffset, int len)

Tests if two string regions are equal.

29 String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

30 String replaceAll(String regex, String replacement

Replaces each substring of this string that matches the given regular expression with the given replacement.

31 String replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the given replacement.

32 String[] split(String regex)

Splits this string around matches of the given regular expression.

33 String[] split(String regex, int limit)

Splits this string around matches of the given regular expression.

34 boolean startsWith(String prefix)

Tests if this string starts with the specified prefix.

35 boolean startsWith(String prefix, int toffset)

Tests if this string starts with the specified prefix beginning a specified index.

36 CharSequence subSequence(int beginIndex, int endIndex)

Returns a new character sequence that is a subsequence of this sequence.

37 String substring(int beginIndex)

Returns a new string that is a substring of this string.

38 String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

39 char[] toCharArray()

Converts this string to a new character array.

40 String toLowerCase()

Converts all of the characters in this String to lower case using the rules of the default locale.

41 String toLowerCase(Locale locale)

Converts all of the characters in this String to lower case using the rules of the given Locale.

42 String toString()

This object (which is already a string!) is itself returned.

43 String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the default locale.

44 String toUpperCase(Locale locale)

Converts all of the characters in this String to upper case using the rules of the given Locale.

45 String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

46 static String valueOf(primitive data type x)

Returns the string representation of the passed data type argument.