« Previous Page Next Page »
    

Introduction to Java String Class.

POSTED

AUTHOR: VARUN SINGH

Strings, which are widely used in Java programming, are a sequence of characters. String is basically an object that represents sequence of char values. In java, objects of String are immutable which means a constant and cannot be changed once created.


Creating a String:

The Java platform provides the String class to create and manipulate strings. There are two ways to create string in Java:

• String literal

String s = "Hello World";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world".

• Using new keyword

String s = new String ("Hello World");

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

Java String Example:

// Java program to demonstrate String 
public class StringExample
{  
	public static void main(String args[])
	{  
	//creating string by java string literal 
	String s1="java"; 
	char ch[]={'s','t','r','i','n','g'}; 
	
	//converting char array to string  
	String s2=new String(ch);
	
	//creating java string by new keyword 
	String s3=new String("example"); 
	
	System.out.println(s1);  
	System.out.println(s2);  
	System.out.println(s3);  
   }
}

Output:

java
string
example


Java String Methods:

Here are the list of the methods available in the Java String class. These methods will be explained together in a single program.

1. int length() Method:

Returns the number of characters in the String.

"CoderGlass".length();  // returns 10

2. Char charAt(int i) Methods:

Returns the character at ith index.

"CoderGlass".charAt(3); // returns  'e'

3. String substring (int i) Methods:

Return the substring from the ith index character to end.

"CoderGlass".substring(3); // returns  'erGlass'

4. String substring (int i, int j) Methods:

Returns the substring from i to j-1 index.

"CoderGlass".substring(2, 5); // returns  'der'

5. String concat( String str) Methods:

Concatenates specified string to the end of this string.

String s1 = "Coder";
String s2 = "Glass";
String output = s1.concat(s2); // returns "CoderGlass"

6. int indexOf (String s) Methods:

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

String s = "Coderglass Programming Blog";
int output = s.indexOf("Programming"); // returns 11

7. int indexOf (String s, int i) Methods:

Returns the index within the string of the first occurrence of the specified string, starting at the specified index.

String s = "Coderglass Programming Blog";
int output = s.indexOf('g',3); // returns 5

8. int lastindexOf( int ch) Methods:

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

String s = "Coderglass Blog";
int output = s.lastindexOf('o'); // returns 13

9. boolean equals( Object otherObj):

Compares this string to the specified object.

Boolean out = "Coderglass".equals("Coderglass"); // returns true
Boolean out = "Coderglass".equals("coderglass"); // returns false

10. boolean equalsIgnoreCase (String anotherString):

Compares string to another string, ignoring case considerations.

Boolean out = "Coderglass".equals("Coderglass"); // returns true
Boolean out = "Coderglass".equals("coderglass"); // returns true

11. String toLowerCase():

Converts all the characters in the String to lower case.

String s1 = "CoderGlass";
String s2 = word1.toLowerCase(); // returns "coderglass"

12. String toUpperCase():

Converts all the characters in the String to upper case.

String s1 = "CoderGlass";
String s2 = word1.toLowerCase(); // returns "CODERGLASS"

13. String trim():

Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.

String s1 = " Coder Glass ";
String s2 = s1.trim(); // returns "Coder Glass"

14. String replace (char oldChar, char newChar):

Returns new string by replacing all occurrences of oldChar with newChar.

String s1 = "PoderGlass";
String s2 = "PoderGlass".replace('P' ,'C'); // returns "CoderGlass"

Program to illustrate all string methods:

// Java code to illustrate different constructors and methods 

import java.io.*;
import java.util.*;
class Test
{
    public static void main (String[] args)
    {
        String s= "CoderGlass";
       

        // Returns the number of characters in the String.
        System.out.println("String length = " + s.length());

        // Returns the character at ith index.
        System.out.println("Character at 3rd position = " + s.charAt(3));

        // Return the substring from the ith  index character to end of string
       
        System.out.println("Substring " + s.substring(3));

        // Returns the substring from i to j-1 index.
        System.out.println("Substring  = " + s.substring(2,5));

        // Concatenates string2 to the end of string1.
        String s1 = "Coder";
        String s2 = "Glass";
        System.out.println("Concatenated string  = " + s1.concat(s2));

        // Returns the index within the string of the 
		//first occurrence of the specified string.
       
        String s4 = "CoderGlass Programming Blog";
        System.out.println("Index of Programming " + 
                           s4.indexOf("Programming"));

        // Returns the index within the string of the
        // first occurrence of the specified string, starting at the specified index.
      
        System.out.println("Index of a  = " + s4.indexOf('a',3));

        // Converting cases
        String w1 = "CoderGlass";
        System.out.println("Changing to lower Case " + w1.toLowerCase());

        // Converting cases
        String w2 = "CoderGlass";
        System.out.println("Changing to UPPER Case " + w1.toUpperCase());

        // Trimming the word
        String w4 = " Coder Glass ";
        System.out.println("Trim the word " + w4.trim());

        // Replacing characters
        String str1 = "poderglass";
        System.out.println("Original String " + str1);
        String str2 = "poderglass".replace('p' ,'c') ;
        System.out.println("Replaced p with c -> " + str2);
    } 
}

Output

String length = 10
Character at 3rd position = e
Substring erGlass
Substring  = der
Concatenated string  = CoderGlass
Index of Programming 11
Index of a  = 7
Changing to lower Case coderglass
Changing to UPPER Case CODERGLASS
Trim the word Coder Glass
Original String poderglass
Replaced p with c -> coderglass



The End:

Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section. We will be very happy to hear that.

If you like my tutorial, please follow us on facebook, Google + and Twitter. I need your support to continue.

« Previous Page Next Page »

Comments: