String in java

Collection of character is refer to us as a string.

Java supports two types of string

  1. Immutable string
  2. Mutable string

Immutable string

All the string whose value can not be changed once they are initialized are refereed as Immutable string. Immutable string can be created in two ways.

type 1 : String s = " Hello ";
type 2 : String s = new String(" Hello ");

here ” “  double quotes must be used while initializing string.

Note:In java charater level access is not provided so the string can not be changed after initialization, so they are called as Immutable.
Example: System.out.println(s[0]);     // this will give error

if data in the string is continuously changing then we should not use immutable string in program , instead we should use mutable string as follows.

Mutable string

All those string whose values can be changed after initialization is refer to us as a Mutable string.

To declare the string any one of the following in-built class can be used.

StringBuffer or StringBuilder

Example :

class MutableDemo{
    public static void main(String args[]){
        StringBuffer s = new StringBuffer(" Hello ");
        System.out.println(s);
        s.append("World"); // append method used to modify string
        System.out.println(s);
   }
}

Output: Hello
        Hello world

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: