C/C+ treats string as an array of character, But in Java string is an object of String class, String is a class as well as data type in Java, Here Example of String data type is: String s=”Indian”,Here ‘s’ is a variable of data type ‘String’.
In Java we can create a string in 3 different process.
In first process JVM creates an object and
stores the string to that object,Object is referenced by s1 variable in this example.Eg: String
s1="My name is Arun";
Second process is we create a String class
object by allocating some memory using new operator and stores the string in the
object.Eg: String
s2=new String("I am from India");
Last one is we create an array of character type and we
pass the array to string object created. Eg: char arr[]={'i','
','l','i','k','e',' ','j','a','v','a'}; //array of type String with characters
String s3=new
String(arr); //passing the arr to string
object.Example of creation of string in Java:
class CreateString
{
public static void main(String args[])
{
String s1="My name is Arun";
String s2=new String("I am from India");
char arr[]={'i',' ','l','i','k','e',' ','j','a','v','a'};
String s3=new String(arr);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
O/P:
My name is Arun
I am from India
i like java
N.B:Java is enriched with various String class(in java.lang package) methods.We will discuss those String class methods with example in next post.
No comments:
Post a Comment