Java String Class

Introduction

Java string variable is an object of type String.

Java string constants are String objects.

For example, in the statement

System.out.println("demo2s.com"); 

The string "demo2s.com" is a String object.

Java String type are immutable.

Once a String object is created, its contents cannot be altered.

To change a string, just create a new one with the modifications.

We can use StringBuffer and StringBuilder to deal with altered strings.

We can create a string:

String myString = "demo2s.com"; 

For example, this statement displays myString:

System.out.println(myString); 

Java can use + operator to concatenate two strings.

For example, this statement

String myString = "demo2s" + "." + "com"; 

results in myString containing "demo2s.com"

The following program shows how to add string together:

// Demonstrating Strings.
public class Main {
  public static void main(String args[]) {
    String strOb1 = "demo2s";
    String strOb2 = ".com";
    String strOb3 = strOb1 + strOb2;

    System.out.println(strOb1);//from  w ww . j a  v a2s  .c  om
    System.out.println(strOb2);
    System.out.println(strOb3);
  }
}

We can test two strings for equality by using equals().

We can obtain the length of a string by calling the length() method.

We can obtain the character at a specified index within a string by calling charAt().

The general forms of these three methods are shown here:

boolean equals(secondStr)  
int     length()  
char    charAt(index) 

Here is a program that demonstrates these methods:

// Demonstrating some String methods.
public class Main {
  public static void main(String args[]) {
    String strOb1 = "demo2s";
    String strOb2 = ".com";
    String strOb3 = strOb1;/*from  w  w  w .  j a v a2  s  .  co  m*/

    System.out.println("Length of strOb1: " + strOb1.length());

    System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));

    if(strOb1.equals(strOb2)) 
      System.out.println("strOb1 == strOb2");
    else
      System.out.println("strOb1 != strOb2");

    if(strOb1.equals(strOb3)) 
      System.out.println("strOb1 == strOb3");
    else
      System.out.println("strOb1 != strOb3");
  }
}

The following code creates arrays of strings:

// Demonstrate String arrays.
public class Main {
  public static void main(String args[]) {
    String str[] = { "one", "two", "three" };
    // w w w  . j  a va2  s  .  c o m
    for(int i=0; i<str.length; i++)
      System.out.println("str[" + i + "]: " +
                          str[i]);
  }
}



PreviousNext

Related