Translate

Tuesday 26 August 2014

String class

String is basically group of characters. e.g Dipesh  this word is made of 6 characters and is a string.

Creating a String object:-
String s1 = null;
String s1 = "Java";
String s3 = new String('Java');

String class objects are immutable objects which means that they can't be changed. It always creates a new object when we try to change them.

String s1 = "ab";     //s1 is pointing to a memory location which has ab
s1 = s1 + "cd";      //as discussed earlier + concatenates two strings. Here s1 starts pointing to a new                                                         memory location which has abcd.

Array of strings:-
We can define an array of strings in the same way we define an array of primitive data types.
String arr[ ]=new String[ 5 ];
We can also assign values to them as we do it primitive data types.
arr[0] = "c++";
arr[1] = "Java";
arr[2] = "c";

for(int i=0; i<arr.length; i++)
      System.out.print(arr[i]);

length:-
It is used to determine number of character in String object.
String str = "abcd";
System.out.print(str.length);

replace( ):-
It is used to replace  a character with another character through out a String.
String s = "Java";          //s is pointing to a memory location which has java
s = s.replace('a','b');     //now s is pointing to a new memory location which has jbvb

Comparing Strings:-
== (equality operator) can't be used to compare 2 string object or any other class objects. It performs shallow comparison i.e. it compares that 2 reference variable hold same reference or not.
equals( ):- It is used to perform deep comparison i.e. it compares whether content of 2 string object are equal or not. It is case sensitive.


No comments:

Post a Comment

Total Pageviews