The String Class
In java String is implemented through String class.
Remember that any keyword starting with a capital letter is a class.The String class is defined in the package ‘java.lang’, which is automatically imported in all java programs.
The ‘String’ class is declared as final, hence cannot be sub-classed.
The ‘String’ object represents a fixed length immutable character sequence.
String Constructors
- String()
- String(char arr[])
- String(char arr[],int startIndex,int numChars)
- String(String s)
- String(byte arr[])
- String(byte arr[], int startIndex, int numChars)
String s; // way to make reference of String
1. String()
s = new String(); // creates an empty String
2.String(char str[])
char str[] = {'t','e','n','d','u','l','k','a','r'}; s = new String(str); //s is referring to "tendulkar"
3. String(char arr[],int startIndex,int numChars)
s = new String (str, 2 , 3 ); // s is now referencing to "dul"
4. String(String s) // - - - > copy constructor
s = new String("Vivek"); // invokes copy constructor, hence creates a new object
v/s
s = "Vivek"; // does not invokes constructor. The String is created in String pool & its reference is assigned to s;
5. String(byte arr[])
byte arr[] = {118,105,118,101,107};
s = new String(arr); // s is referred to "vivek"
5. String(byte arr[], int startIndex, int numChars)
s= new String(arr, 1 , 3 ); // s refers to "vek"
No comments:
Post a Comment