Virtual Science Headline Animator

Virtual Science

Search

Thursday, February 10, 2011

Java String Class

Strings in java

Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation.
Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.

Java.lang.String class creation

A simple String can be created using a string literal enclosed inside double quotes as shown;
String str1 = “My name is bob”;
Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.
If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon.
String str1 = “My name is bob”;
String str2 = “My name is bob”;
String str3 = “My name ”+ “is bob”; //Compile time expression
String name = “bob”;
String str4 = “My name is” + name;
String str5 = new String(“My name is bob”);

In the above code all the String references str1, str2 and str3 denote the same String object, initialized with the character string: “My name is bob”. But the Strings str4 and str5 denote new String objects.
Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (”"), using the string concatenation operator (+).
public class StringsDemo {

    public static void main(String[] args) {

     byte[] bytes = {2, 4, 6, 8};

     char[] characters = {'a', 'b', 'C', 'D'};

     StringBuffer strBuffer = new StringBuffer("abcde");

//     Examples of Creation of Strings

     String byteStr = new String(bytes);      

     String charStr = new String(characters); 

     String buffStr = new String(strBuffer);

     System.out.println("byteStr : "+byteStr);

     System.out.println("charStr : "+charStr);

     System.out.println("buffStr : "+buffStr);

    }

}
 
Download :http://www.javabeginner.com/java-string.zip 

No comments:

Post a Comment