Course Title:: Modern Programming Tools and Techniques-I
Course Title:: Modern Programming Tools and Techniques-I
Strings
Strings:
A String represents group of characters. Strings are represented as String objects in java.
Creating Strings:
We can declare a String variable and directly store a String literal using assignment operator.
String str = "Hello";
We can create String object using new operator with some data.
String s1 = new String ("Java"); This is not a String. char arr[] = { 'p','r','o',g,r,a,m};
We can create a String by passing array name and specifying which characters we need:
String s3 = new String (arr, 2, 3);
Here starting from 2nd character a total of 3 characters are copied into String s3.
Note: We can divide objects broadly as mutable and immutable objects. Mutable objects are those objects whose contents can be modified. Immutable objects are those objects, once created can not be modified. String objects are immutable. The methods that directly manipulate data of the object are not available in String class.
StringBuffer
StringBuffer: StringBuffer objects are mutable, so they can be modified. The methods that directly manipulate data of the object are available in StringBuffer class.
Creating StringBuffer:
We can create a StringBuffer object by using new operator and pass the string to the object, as:
StringBuffer sb = new StringBuffer (Ram");
We can create a StringBuffer object by first allotting memory to the StringBuffer object using new operator and later storing the String into it as: StringBuffer sb = new StringBuffer (30);
In general a StringBuffer object will be created with a default capacity of 16 characters. Here, StringBuffer object is created as an empty object with a capacity for storing 30 characters. Even if we declare the capacity as 30, it is possible to store more than 30 characters into StringBuffer. To store characters, we can use append () method as: Sb.append (Ram);