Java String
1.In
c/c++
string are stored in array of character terminated by null character.
2.But
in java have inbuilt class string.
3.Class
string define in java.lang
package.
4.String
in java are immutable that means you can not modify any character from a
string.
5.In
c/c++ we
can modify string.
Declaring
and constructing string:
Four
ways to construct string.
1. String s1=new String(“Good Morning”);
2. String s2;
S2=“Good Morning”;
3. char []ar={‘C’,’H’,’O’,’U’,’B’,’E’,’Y’};
String S3=new String(ar);
4. String s4=new String(); //it
creates empty or null string
System.out.println(s1);
Or
System.out.print(s1);
S1=s2;
Copying
one string into other:
We know that string is immutable and can not be modified, it is true.This case is treat as exception.Actually string is an object and variable name are object reference hence it is possible for a given reference to point to another string.
Comparing
string:
•There
is two method to compare string.
•first
is
S1.equals(s2);//case sensitive
S1.equalsIgnoreCase(s2);//ignore case
•These
method gives Boolean result i.e. true or false.
to another string.
•Second
type of comparison:
S1.compareTo(s2);
•It
returns integer value ,+ve,zero,-ve.
•If
we want to know that one string is less than , equal to or greater than another
string lexicographicaly then
use this method.
Example
string Program:
import java.lang.*;
/* this package by default included,
if i dont write this line then it will not give error.*/
class string2
{
public static void main(String ar[])
{
String s1=new String("Rahul");
String s2=new String("sant");
String s3=new String("choubey");
String s4=new String(“choubey");
int i,j,k;
i=s4.compareTo(s1);
j=s4.compareTo(s3);
k=s4.compareTo(s2);
System.out.println("s4&s1="+i);
System.out.println("s4&s3="+j);
System.out.println("s4&s2="+k);
}
}
No comments