Tuesday, 21 January 2014

Exploring the string class

how to use string classes:creating string

String class:

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.One very important thing to notice about String is that String object are immutable that means once a String object is created, its contents cannot be altered. However if you need to change a String, you can do it by creating a new String object.. string you create is actually an object of type String. Even string constants are actually String objects. 
For example, in the statement  System.out.println("This is a String, too"); the string “This is a String, too” is a String constant.

Creating a String

String can be created in number of ways. Here are few ways of creating a String object 

String s="Hello";
String str=new String(s);
String str1=new String("Java");
String str2=s+str1;
String str3="HelloJava";
String str4=str3;

Example for string class

// Demonstrating Strings.
class StringDemo
{
public static void main(String args[])
{
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}

The output produced by this program is shown here:

First String
Second String
First String and Second String

No comments:

Post a Comment