Tuesday, 2 February 2016

String

By
A set of related character is represented using String 

In Java,string is handled using String class
In C,string is  implemented using array of characters which leads to a problem of wastage of memory or lack of memory as the size of array is fixed but in Java string is handled using String class.

Creation and Initialization of String Object
Method 1:
               String string_var = new String("Name");
Method 2:
               String string_var;
               string_var = "name";
Method 3:
               String string_var = "name";

Here, using method 1 two objects are created one in the Heap and another in the constant pool where String object are actually stored.

Using method 2 and 3 only one object is created which is in constant pool. also called String pool


  • string_var is a reference variable of String class and here it is assumed that it is declared inside main() method so stored in Stack and name is object so stored in Heap
  • The default value of Sting class reference variable is null 
String is Immutable i.e can not be Modified
Lets understand the concept of immutable String

Consider a statement :
String string_Name = new String("Ashish");//1
string_Name = "Kumar";//2

 After executing line //1


After executing line //2

Firstly string_Name is reference variable for "Ashish" in line //1
and after assigning string_Name with "Kumar" in line //2
string_name variable is no logger refering to "Ashish"  but to "Kumar"  and "Ashish" is still in the memory without reference 

Immutable means once the Object of String class is created it cannot be altered

String object are case-sensitive "jack".equals("JAck") ; will result into False
String class have many method that facilitate easy operation on strings
Method of String class
  • int length : used to find number of characters in string
  • String concat(String s): used to concatenates two strings and return third string
  • boolean equals(String s): case sensitive string equality is checked
  • boolean equalsIgnoreCase(String s): case insensitive string equality is checked
  • String toUpperCase(String s):Returns a string that contains all the characters of the source string converted to upper case
  • String toLowerCase(String s):Returns a string that contains all the characters of the source string converted to lower case.








0 comments :

Post a Comment