Sei sulla pagina 1di 9

STRINGS

Most of the data that transmits on the internet will be in the form of group of groups of
characters.
Such groups of characters are called strings.
Suppose if you want to pay your mobile bill through online we need to give your credit
card no, expiry dateetc. which are all nothing but strings only. So a string represents
group of characters.
Creating Strings:
There are three ways
1) We can create a string just by assigning a group of characters to a String type
variable.
String s;
s=hello;
2) We can create a strings by using new operator.
String s=new String(hello);
3)The way to create strings by converting arrays to strings. Let us take a character type
array: arr[]
with some characters
Char ch[]={m,i,n,q}
String str=new String(ch);
String class methods:
String concat(String s): It Combines the two strings
Ex: String s3=s1.concat(s2);
String s1=Hydera String s2=bad;
String s3=s1.concat(s2);
By using + operator also we can combine two or more strings.
String s=s1+s2+s3+s4;
int length((): it gives the length of string.
Ex:s.length();
charcharAt(int i) :This method returns the character at specified location i.suppose we
can call this method s1.cahrAt(6) it gives 6th character in the string.
intcompareTo(String s1): This method compares the two string if two string are same it
return 0.if s1>s2 it returns +ve no. if s1<s2 it returns ve no. if s1==s2 it returns 0;
intcompareToIgnoreCase(String s1): Same as compareTo() method it. But it does not
take case of strings into consideration.

boolean equals(String s): This method returns true if both strings are true. Otherwise
false.it is case sensitive.
booleanequalsIgnoreCase(String):Same as above but it is in case insensitive.
booleanstartWith(String s): This method returns true if the string start with the string s.
Other wise false. This method is case sensitive.
booleanendsWith(String s): This method returns true if the string ends with the string s.
Other wise false. This method is case sensitive.
intindexOf(String s): This method is called in the form of s1.indexOf(s2) and it returns
an integer value, if s1 contains s2 as sub string then the first occurrence position in the
string will be returned.
intlastIndexOf(String s):This method same as above but it returns last occurance.
String replace(char ch1,char ch2): This method replaces all the occurrences of character
c1 by new character c2.
String substring(int i): This method is useful to extract sub string from main string.This
method returns a new String consist of all charactes which are starting form postion i to
until end of the string.
String substring(int i1,int i2): This method is useful to extract sub string from main
string.This method returns a new String consist of all charactes which are starting form
postion i1 toi2.
String toLowerCase();This method converts all the characters in the string to Lowercased
string.
String toLowerCase();This method converts all the characters in the string to uppercased
string.
String trim(): This method removes space from the beginning and ending of a string.
voidgetChars(int i1,int i2,char arr[],int i3): This method copies characters from string
into character array. The characters starting from postion i1 to i2-1 in the string are
copied into the array.
String[] split(delimiter): This method is useful to break the string into pieces at places
represented by the delimiter. The resultant pieces are turned into string array.
Write a program which help us to understand how to create strings and how to use some
important methods of string class

importjava.lang.*;
class Srr1
{
public static void main(String args[])
{
String s1="this is a hello";
String s2="hai";
int n1=s1.length();
int n2=s1.charAt(3);
int n3=s1.compareTo(s2);

boolean x=s1.equals(s2);
boolean x1=s1.equalsIgnoreCase(s2);
boolean x2=s1.startsWith("he");
boolean x3=s1.endsWith("lo");
int n4=s1.indexOf("is");
int n5=s1.lastIndexOf("is");
String str=s1.replace('i','t');
String p=s1.subString(0,6);
String q=s2.subString(0);
System.ou.println(p+q);
String str3=s1.toUpperCase();
String str4=s1.toLowerCase();
String str5=s1.trim();
String str6=s1.concat(s2);
System.out.println(n1);
System.out.println(n2);
System.out.println(n3);
System.out.println(x1);
System.out.println(x2);
System.out.println(x3);
System.out.println(n4);
System.out.println(str);
System.out.println(p+q);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
System.out.println(str6);
System.out.println(x);
System.out.println(n5);
}
}
Let us take a string and copy some of the characters of the strings into a
character array arr using getChars() method
Class strcpy{
Public static void main(String args[]){
String str=Hello,this is a book on java;
chararr[]=new char[20];
str.getChar(7,21,arr,0)
Ssystem.out.println(str);
}}
Write a program for splitting a string into pieces wherever a space is found.
Class strsplit{
public static void main(String args[]){
String str= Hello this is a book on Java
String[] s;
s=str.split( );
for(int i=0; i<s.length; i++)
System.out.println(s[i]);

}}

String objects are immutable


What is immutable?
If you do any modification to existing object. It will not update it always create new
object.
In the below example:
String str1="hai";
str1=str1+"bye";
In the above example it creates one string object str1 is pointing to the object. Here
bye String we are adding to str1. it is not adding to str1 it creates new object with
these chages(haibye). And str1 is pointing to the above object.

In the above Diagram str1 is pointing to hai object. After doing your modification the
string got (haibye) For the modification it creates new String object and str1 is pointing
to new Object. The old object is destroyed. Because of this String object are immutable.
What is the difference between normal creation(String str1=hai) and by using new
operator(String str1=new String("hai")).
By normal creation(String str1=hai))
First it will check in String constant pool whetherthe String is there or not if it there it will
use that object if it is not there it will creates new object.
Ex:
String str1=hai
String str2=hai;
First it will check in String constant pool it is not there it will creates new object.In
second statement also we are creating same string hai it can notcreates new object.
In String constant pool already hai object is there just str2 is pointing to same object .

Here two reference are pointing to same object if use (==) to compare the two String is
gives true.
System.out.println(str1==str2); true. //two references pointing to same object thats
way it gives true.
String str1=new String(hai);
String str2=new String(hai);
It always creates new object in heap memory not in String constant pool why because
we are using new operator. Here we are creating two string with same data.

.
In string suppose if we do n number of modification it will creates n object.
String str1="hai";
str1=str1+" welcome ";
str1=str1+"to"+" java";
str1=str1+"this "+" for String class";
here it creates 4 objects. Dont you think that is wastage of memory?
Yes. Beacause of this String buffres are came.
Suppose if we are frequently changing the String dont use Strings use String Buffers.
Already we know strings are immutable and cannot be modified. To overcome this we
got another class String buffer which represents string in such a way that their data can
be modified. It means StringBuffer class objects are immutable. And there are methods
provided in this class which directly manipulate the data inside the object.
Creating String Buffer Objects:
There are two ways to create the String Buffer objects.
StringBuffersb=newStringBuffer("hello");
System.out.println(sb);
It displays hello.

Another way of creating a StringBuffer object is to first allotting memory to the


StringBuffer object using new operator and later storing the string into it.
StringBuffersb=new StringBuffer();
Here we are creating StringBuffer object as an empty object as an empty object and not
passing any string to it. In this case, a stringBuffer object will be created with default
capacity is 16 characters.
StringBuffer sb2=new StringBuffer(50);
Here we are creatingStringBuffer any empty object with a capacity of storing 50
characters. Of course, even if we are declare the capacity as 50, it is possible to store
more than 50 characters into this StringBuffer. The reason is StringBuffre is mutable and
can be expand dynamically in memory.

StringBuffer class methods:


StringBuffer append(x): x may be boolean ,byte, int,
long,float,double,char,characterarray.string or another StringBuffer.
StringBuffersb=newStringBuffer("hello");
sb.append("welcome to java");
StringBufferinsert(inti,x):x may be boolean ,byte, int,
long,float,double,char,characterarray.string or another StringBuffer. It will be inserted
into the StringBuffer at the position represented by i.
StringBuffer sb2=newStringBuffer(50);
sb2.append("hello");
sb2.insert(5, "srinu");
StringBufferdelete(inti,int j): This removes the characters form 1th positions till j-1th
position in the StringBuffer.
Sb.delete(0,3) deletes the characters from the beginning to 2ndcharacters.
StringBufferreverse(): This reverse the characters sequence in StringBuffer. If
StringBuffer contain abc.it becomes cba.
String toString() : it converts StringBuffer object to String object.This will enable us to
use String class methods on stringBuffer object, after its convertion .
Intlength(): This returns no of characters are there in the StringBuffer object.
IntindexOf(String str): This returns the first occurrences of substring str in the
StringBuffer object For example.

StringBuffersb=newStringBuffer("This is a book");
System.out.println(sb.indexOf("is"));
Observe the substring is occurred starting at 2ndpostion and 5thpositions(counting from
0). Indexof() method returns first occurrence only.so the preceding statement gives 2.
IntlastIndexOf(String str): This returns the last occurrences of substring str in the
StringBuffer object For example.
StringBuffersb=newStringBuffer("This is a book");
System.out.println(sb.indexOf("is"));
Observe the substring is occurred starting at 2ndpostion and 5thpositions(counting from
0). Indexof() method returns last occurrence only.so the preceding statement gives 5.
StringBufferreplace(intI,intj,Stringstr): This replace the characters from i to j-1,by the
String str in the StringBuffer object. For Example.
StringBuffersb=newStringBuffer("High cost");
sb.replace(0, 4, "Low");
we are replacing first 4 characters of sb by the 3 characters,Low. Now sb contain Low
cost.
String substring(int i): This retrieves a substring form the StringBuffer object starting
from ithposition till end.
StringBuffersb=newStringBuffer("High cost");
System.out.println(sb.substring(2));
Preceding statement retrieves the characters from 2nd position to till end. Hence it
returns gh cost
String substring(inti,int j): This extracts a substring form StringBuffer object starting
form ith position to j-1th position. Forexample
StringBuffersb=newStringBuffer("Highi cost");
System.out.println(sb.substring(2,5));
Preceding statement retrieves the characters from 2nd position to 4thposition. Hence it
returns ghi
StringBuilder Class
StringBuilder class has been added in jdk 1.5 which has same features like StringBuffer
class. StringBuilder class objects are also mutable as are the StringBuffer objects.
For example to create StringBuilder class, we can use any of the following statements:
StringBuilder sb=new StringBuilder(Hello);
StringBuilder sb=new StringBuilder();
StringBuilder sb=new StringBuilder(50);
StringBuilder class methods: the following are the important methods in StringBuilder
class, which are functionally similar to the methods of StringBuffer class discussed
previously:

StringBuilder append(x)
StringBuilder insert(int i,x)
StringBuffer delete(int i,int j)
StringBuffer reverse()
StringBuilder toString()
int length();
int indexOf(String str)
int lastIndexOf(String str)
StringBuilder replace(int i,int j,String str)
String substring(int i)
String substring(int I,int j)
The main difference between StringBuffer and StringBuilder classes is that the
StringBuffer class is synchronized by default and StringBuilder class is not. This means,
when several threads process or act on a stringBuffer class object, they are executed
one by one on the object, thus ensuring reliable results. But in case of StringBuilder
object, since it is not synchronized, it allows several thread to act on it simultaneously.
This may lead to inaccurate results in some cases.
Synchronizing the object is like locking the object. This means, when a thread acts on
the object, it is locked and any other should wait till the current thread completes and
unlocks the object. Thus, synchronization does not allow more than 1 thread to act
simultaneously on the object. Implementing the synchronization mechanism(like locking
and unlocking of the object) will take some time for the JVM. Hence StringBuffer class
will take more time for the JVM. Hence StringBuffer class will take more execution time
than StringBuilder, which does not implement this mechanism.
StringTokenizer class
This class is useful to break a string into pieces, called tokens. These tokens are then
stored in the StringTokenizer object from where they can be retrieved. The code to
create an object to StringTokenizer class is
StringTokenizer st=new StringTokenizer(str,"delimite");
In the preceding statement, the actual string str is broken into pieces at the positions
marked by a group of characters, called delimiters. For example, to break the string
wherever a comma is found, we can write
StringTokenizer st=new StringTokenizer(str,,);
Similarly to break the string wherever a comma or colon or both are found , we can use:
StringTokenizer st=new StringTokenizer(str,,:);
StringTokenizer class methods
int countTokens(): This method counts and returns the number of tokens available in a
StringTokenizer object.
boolean hasMoreTokens():This method test if there are more tokens available in the
StringTokenizer object or not. If next token is there it returns true else false.
String nextToken(): This method returns the next token from the StringTokenizer.

Sample program on StringTokenizer class:

package org.sample;
import java.util.StringTokenizer;
public class StringTokenizerDemo {
public static void main(String[] args) {
//take astring
String str="he:+is:+a:+gentle:+man";
//break into tokens at :+.here delimiter is a :+
StringTokenizer st=new StringTokenizer(str,":+");
//retrieve tokens from st and display
System.out.println("tokens are:");
while(st.hasMoreElements()){
String one=st.nextToken();
System.out.println(one);
}
}
}
O/P:

tokens are:
he
is
a
gentle
man

Potrebbero piacerti anche