What are the different way if creating String in Java?

There are 3 way of creating string in Java.
a) We can create a string just by assigning a group of characters to a string type variable.

String s = "hello";

b) We can create an object to String class  by allocating memory using new operator. This is just like creating an object to any class.

String s = new String ("hello");

Here we doing two things. First, we creating object using new operator. Then, we are storing the string: "hello" into the object.

c) The third way of creating the strings is by converting the character arrays into strings. Let us take a character type array: art[  ].

char arr[  ] = { 'c' , 'h' , 'a', 'i' , 'r', 's' } ;

Now create a string object by passing the array name to it, as:
String s = new String (arr) ;

Now the string s contains the string value "chairs" . This means all the characters of the array into the string.

Note

String s = new String (arr, 2, 3);

Here, starting from 2nd character a total of 3 characters are copied into the string s., the 0th character in the array is 'c' and the 2nd character is 'a' . Staring from 'a', a total of three characters implies 'air'. So these three characters are copied into the string s.

No comments:

Post a Comment