Thursday, December 9, 2010

String's

1. Introduction

            In Java strings are objects designed to represent a sequence of characters. Because character strings are commonly used in programs, Java supports the ability to declare String constants and perform concatenation of Strings directly without requiring access to methods of the String class.

 A Java String is read-only and once created the contents cannot be modified.

String buffers support mutable strings. Because String objects are immutable they can be shared

2. Declaring and Allocating Strings


         The String class has 13 different constructors. Only the most common constructors will be presented. For complete information on the String class, access Oracle's Java API page at http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html


The simplest method to create a String object is to enclose the string literal in quotes and assign the value to a String object. Creation of a String through assignment does not require the use of the new operator, for example
                      For example:

                               String str = "abc";    is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);

              Alternatively, String objects can be created through constructors. The following constructors are supported:

public String()
Constructs a new String with the value "" containing no characters. The value is not null.


public String( String value )
Constructs a new String that contains the same sequence of characters as the specified String argument.

public String( char[] value )
Constructs a new String containing the same sequence of characters contained in the character array argument.

public String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default charset.

public String(StringBuffer buffer)
Allocates new string that contains the sequence of characters currently contained in the string buffer argument.

public String(StringBuilder builder)
Allocates new string that contains the sequence of characters currently contained in the string builder argument.

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2,3);
     String d = cde.substring(1, 2);

3. String Concatenation

Work in progress....

No comments:

Post a Comment