A string is a collection of
characters. Java implements strings as
object type of String. Java provides
three types of string handling classes.
1.
String Class
2.
StringBuffer Class
3.
StringTokenizer Class
String and StringBuffer classes are
defined in java.lang pacakage.
StringTokenizer are defined in java.util package.
1. String Class:
A string is an object of class
String. String literals or constants
written as a sequence of characters in double quotes. A string may be assigned in declaration to
string reference as
String
color = ”blue”
It initializes string reference
color to refer the anonymous string object blue.
Note: 1. Once we create a string object, we cannot change the contents
of string instance.
2.
A variable declared as a string reference can be changed at any time.
String Constructors: String
class provides several types of constructors.
They are
a) String(
): It creates an empty string with no characters in it.
b) String(String):
It takes one String as a parameter.
c) String(StringBuffer):
Allocates a new string that contains the sequence of characters currently
contained in the string buffer argument.
d) String(byte[]
bytes): Construct a new
String
by converting the specified array of bytes using the platform's default character
encoding.
e) String(bytes
byte[], int startindex, int numberofcharacters): Allocates new string
positioned with the startindex by counting the number of charactes.
f) String(char
chars[]): Creates a string initialized by an array of characters.
g) String(char
chars[], int startindex, int numberofcharacters): Creates a string initialized
by an array of characters with the startindex by counting the number of
charactes.
Methods:
1. int length( ): It returns the number
of characters in a given string.
Example:
String s1=new String(“hello”);
System.out.println(s1.length());
class
len
{
public
static void main(String[] args)
{
String
s1=new String("hello");
System.out.println(s1.length());
}
}
2. char charAt(int where): It
returns the character at the specified location. “where” must be a nonnegative specified
location within the string. The first
element of a string is considered to be at position “zero”.
Example:
class pos
{
public
static void main(String[] args)
{
String
s1=new String("hello java");
char
c=s1.charAt(7);
System.out.println("character="+c);
}
}
3. void getChars(int
sourcestart, int sourceend, char target[], int targetstart): It extracts
more than one character at a time and copy the characters of the string into a
character array.
The
first argument is the starting index from which characters are copied in the
string. The second argument is the index
that is one part of the last character to be copied from the string. The third argument is the array into which
the characters are copied. The last
argument is the starting index where the copied characters are placed in the
character array.
Example:
class get
{
public
static void main(String[] args)
{
String
s1="java programming language";
char
c[]=new char[10];
s1.getChars(3,8,c,0);
for(int
i=0;i<(8-3);i++)
System.out.print(c[i]);
}
}
O/P: a prog
4. boolean equals( ): It
compares the two strings and returns true if the strings contain the same
characters in the same order, and false otherwise. The comparison is case-sensitive.
Syntax: boolean equals(Object string);
Example:
class equal
{
public
static void main(String[] args)
{
String
s1=new String("india ");
String
s2=s1;
if(s1.equals(s2))
System.out.println("Strings
are Equal");
else
System.out.println("Strings
are not Equal");
}
}
5. boolean equalsIgnoreCase( ):
It compares the two strings and returns true if the strings contain the same
characters in the same order, and false otherwise by ignoring the case characters.
Syntax: boolean equalsIgnoreCase(String
str);
Example:
class equall
{
public
static void main(String[] args)
{
String
s1=new String("india ");
String
s2=new String(“InDia ”);
if(s1.equalsIgnoreCase(s2))
System.out.println("Strings
are Equal");
else
System.out.println("Strings
are not Equal");
}
}
6.
int compareTo(String str ): It returns ‘0’ if the two strings are
equal. ‘Negative number’ if the invoking
string is less than str and ‘postivite number’ if the invoking string is
greater than str that is passed as an argument. The comparision is
case-sensitive.
Example:
class
comp
{
public static void main(String[]
args)
{
String s1=new
String("hello");
String s2=new
String("india ");
if((s1.compareTo(s2))>0)
System.out.println("S1
is greater than s2");
else
if((s1.compareTo(s2))<0)
System.out.println("S2
is greater than s1");
else
System.out.println("Two
stings are equal");
}
}
O/P: S2 is greater than s1
If we want to ignore case
differences when comparing two strings, we use the syntax of the form: int compareToIgnoreCase(String str)
This
method was added by Java 2.
7.
regionMatches( ): It compares a specific region inside a string with
another specific region in another string.
It follows two methods.
1.
boolean regionMatches(int startIndex, String str2, int
str2StartIndex, int numchars)
2.
boolean regionMatches(boolean ignoreCase, int
startIndex, String str2, int str2StartIndex, int numchars)
The
first argument is the starting index of the string that invokes the method. The second argument is a comparison
string. The third argument is starting
index in the comparison string. The last
argument is the number of characters to compare between the two strings. IgnoreCase is true the method ignores the
case of the objects being compared.
Example
1:
class
rmatch1
{
public static void main(String[]
args)
{
String s1=new
String("happy birthday");
String s2=new
String("Happy birthday");
if(s1.regionMatches(0,s2,0,5))
System.out.println("Match");
else
System.out.println("Not
Match");
}
}
Example 2:
class
rmatch1
{
public static void main(String[]
args)
{
String s1=new
String("happy birthday");
String s2=new
String("Happy birthday");
if(s1.regionMatches(true,0,s2,0,5))
System.out.println("Match");
else
System.out.println("Not
Match");
}
}
8. int
indexOf(int ch):
int indexOf(String str):
int indexOf(char ch): It search for the first
occurrence of a character. If the
character is found the index of that characters in the string is returned.
Otherwise, it returns ‘-1’.
Example:
class
index
{
public static void main(String[]
args)
{
String letter=new String("Java
programming language");
System.out.println(letter.indexOf('v')); //O/P:
2
System.out.println(letter.indexOf("programming")); //O/P: 5
System.out.println(letter.indexOf('A')); //O/P:
-1
}
}
9.
int indexOf(int ch, int startIndex):
int indexOf(String ch, int startIndex):
int indexOf(char ch, int startIndex): It searches the occurrence of
character from the startIndex argument.
Example:
class
indexof
{
public static void main(String[]
args)
{
String letter=new String("Java
programming language");
System.out.println(letter.indexOf('m',2)); //O/P: 11
}
}
10.
int lastIndexOf(int ch):
int lastIndexOf(char ch):
int lastIndexOf(String ch): It searches the last occurrence of the
character. The search is performed from
the end of the string towards the beginning of the string. If the character is found the index of that
character in the string is return.
Otherwise, it returns ‘-1’.
Example:
class
lindexof
{
public static void main(String[]
args)
{
String letter=new String("Java
programming language");
System.out.println(letter.lastIndexOf('n')); //O/P: 19
System.out.println(letter.lastIndexOf("language")); //O/P: 17
}
}
11.
int lastIndexOf(int ch, int startIndex):
int lastIndexOf(String ch, int
startIndex):
int lastIndexOf(char ch, int startIndex):
It searches the last
occurrence of the character starting with the startIndex to search the string
from ending to the beginning.
Example:
class
lindexof
{
public static void main(String[]
args)
{
String letter=new String("Java
programming language");
System.out.println(letter.lastIndexOf('n',11)); //O/P: -1
}
}
12.
String substring(int startIndex): It returns a copy of the sub string that
begins that startIndex and return to the end of the invoking string.
Example:
class
sub
{
public static void main(String[]
args)
{
String s=new
String("Java programming language");
System.out.println(s.substring(8));
}
}
O/P: gramming language
13.
String substring(int startIndex, int endIndex): It returns all the
characters from the beginning index upto but not including the ending index.
Example:
class
s13
{
public static void main(String[]
args)
{
String s=new
String("program");
System.out.println(s.substring(2,5)); //O/P: ogr
}
}
14.
boolean startsWith(String str):
boolean endsWith(String str): The startsWith( ) method determines
whether a given string begins with a specified string or not. Conversely, endsWith( ) method determines
whether string ends with a specified string or not.
Example:
class
s14
{
public static void main(String[]
args)
{
String s=new String("Java is a
program");
if(s.startsWith("is"))
System.out.println("Match");
else
System.out.println("Not
Match");
}
}
//O/P: Not Match
15.
String concat(String str): It concatenates two string objects.
Example:
class
s15
{
public static void main(String[]
args)
{
String s=new String("Java
");
String
s1=s.concat("program");
System.out.println(s1);
}
}
O/P: Java program
16.
String replace(char original, char replacement): It replace all characters
of one character in the invoking string with another character.
Example:
class
s16
{
public static void main(String[]
args)
{
String s="Hello";
System.out.println(s.replace('l','w')); //O/P: Hewwo
}
}
17.
String toLowerCase(): It converts all uppercase characters into lowercase
characters of a string.
Example:
class
s17
{
public static void main(String[]
args)
{
String s="HELLO";
System.out.println(s.toLowerCase()); //O/P: hello
}
}
18.
String toUpperCase():It converts all lowercase characters into uppercase
characters of a string.
Example:
class
s17
{
public static void main(String[]
args)
{
String s="hello";
System.out.println(s.toUpperCase()); //O/P: HELLO }
}
19.
String trim(): It returns a copy of the invoking string from which any
leading and lining white space has been removed.
Example:
class
s18
{
public static void main(String[]
args)
{
String s=" hello";
System.out.println(s.trim());
}
}
20.
char[] toCharArray(): It returns a character array containing a copy of the
characters in a string.
Example:
class
s20
{
public static void main(String[]
args)
{
String s="hello";
char ch[]=s.toCharArray();
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]);
}
}
21.
String toString(): It converts all objects into strings objects.
Example:
class
s21
{
public static void main(String[]
args)
{
Integer i=new Integer(10);
System.out.println(i.toString()); //O/P: 10
}
}
LabProgram
5: Write a program to sort the list of names in ascending order.
class
lab5
{
public static void main(String[]
args)
{
String ch[]={"india ","hai","andhra"};
String temp;
for(int i=0;i<ch.length-1;i++)
{
for (int j=i+1;j<ch.length;j++)
{
if((ch[i].compareTo(ch[j]))>0)
{
temp=ch[i];
ch[i]=ch[j];
ch[j]=temp;
}
}
}
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]);
}
}
2. StringBuffer Class:
Once a string object is created its
contents cannot be changed. But the
StringBuffer class provides the feature of creating and manipulating dynamic
string information i.e., mutable strings.
Every StringBuffer class is capable for storing a number of characters
specified by its capacity. If the
capacity of StringBuffer exceeded the capacity is automatically expanded to
accommodate the additional characters.
StringBuffer Constructors:
a)
StringBuffer(): It is a default StringBuffer Constructor to create
StringBuffer with no characters init and an initial capacity of 16 characters.
b)
StringBuffer(String str): It takes a string argument to create a
StringBuffer containing the characters of the string argument. The initial capacity is the number of
arguments in the string argument + 16.
c)
StringBuffer(int size): It takes an integer argument and creates a
StringBuffer with no characters init.
The initial capacity is specified by the integer.
Example:
class
sb
{
public static void main(String[]
args)
{
StringBuffer s1,s2,s3;
s1=new StringBuffer();
s2=new
StringBuffer("hello");
s3=new StringBuffer(45);
System.out.println(s1.capacity()+s2.capacity()+s3.capacity()); //O/P: 82
}
}
Methods:
1.
int length(): It returns the number of characters in a StringBuffer.
Example:
class
sb1
{
public static void main(String[]
args)
{
StringBuffer s=new
StringBuffer("hello");
System.out.println(s.length()); //O/P: 5
}
}
2.
int capacity(): It returns the number of characters that can be stored in a
StringBuffer without allocating more memory.
Example:
class
sb2
{
public static void main(String[]
args)
{
StringBuffer s=new
StringBuffer("hello");
System.out.println(s.capacity()); //O/P: 21
}
}
3.
void ensureCapacity(): It is provided to allow the programmer to guarantee
that a StirngBuffer has a minimum capacity where capacity specifies the size of
the buffer.
Example:
class
sb3
{
public static void main(String[]
args)
{
StringBuffer s=new
StringBuffer("hello");
s.ensureCapacity(75);
System.out.println(s.capacity()); //O/P: 75
}
}
4.
void setLength(int len): It increase or decrease the length of
StringBuffer.
Example:
class
sb4
{
public static void main(String[]
args)
{
StringBuffer s=new StringBuffer("abcdefghijkl");
s.setLength(5);
System.out.println(s); //O/P: abcde
}
}
5.
char charAt(int where): It returns a character at the specified where
position.
Example:
class
sb5
{
public static void main(String[]
args)
{
StringBuffer s=new
StringBuffer("abcdefghijkl");
System.out.println(s.charAt(7)); //O/P: h
}
}
6.
void setCharAt(int where, char ch): It takes an integer and a character
argument and sets the character at the specified position of the character
argument.
Example:
class
sb6
{
public static void main(String[]
args)
{
StringBuffer s=new
StringBuffer("abcdef"); //O/P: Hbcdef
s.setCharAt(0,'H');
System.out.println(s);
}
}
7.
void getChars(int Sourcestart, int Sourceend, char Target[], int Targetstart): It
copies the sub string of a StringBuffer into character array. Sourcestart specifies the starting index from
which characters should be copied in StringBuffer. Sourceend specifies the index one past the
last character to be copied from the StringBuffer. Target specifies the character array into
which the characters are to be copied.
Targetstart specifies the starting location of the character array from
where the first character should be placed.
Example:
class
sb7
{
public static void main(String[]
args)
{
StringBuffer s=new
StringBuffer("abc def");
char ch[]=new char[s.length()];
s.getChars(3,s.length(),ch,0);
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]); //O/P: def
}
}
8.
StringBuffer reverse(): It returns the reverse contents of the
StringBuffer.
Example:
class
sb8
{
public static void main(String[]
args)
{
StringBuffer s=new
StringBuffer("abcdef");
System.out.println(s.reverse());
}
}
3. StringTokenizer class:
In programming
languages, statements are divided into individual pieces like identifiers,
keywords, and operators etc., called Tokens.
Java provides StringTokenizer class that breaks a string into its
component tokens. This class is
available in java.util package. Tokens
are separator from one another by delimiters (special operators), white space
characters such as blank, tab, new line and carriage return.
StringTokenizer
Constructors:
a)
StirngTokenizer(Stirng str)
b)
StirngTokenizer(Stirng str, String delimiters)
c)
StirngTokenizer(Stirng str, String delimiters,
boolean delimiterAsToken)
In all versions
str is a string that is tokenized.
In
the first version, the default delimiters are used.
In
the second version and third versions delimiters in string that specifies the
delimiters.
In
the third version if “delimiterAsToken” is true then the delimiters also
returned as tokens when the string is tokenized otherwise, the delimiters are
not returned. Delimiters are not
returned as tokens by the first two forms.
Methods:
1.
int countTokens(): Using the current set of delimiters the method
determines the number of tokens left to be tokenized and return the result.
2.
boolean hasMoreTokens(): It returns true if one or more tokens remain in
the string and returns false if there are none.
3.
String nextToken(): It returns the next token as string.
Example:
import
java.util.*;
class
st
{
public static void main(String[]
args)
{
String s=new String("abc def
gh");
StringTokenizer t=new
StringTokenizer(s);
System.out.println(t.countTokens());
while(t.hasMoreTokens())
System.out.println(t.nextToken());
}
}
O/P: 3
abc
def
gh
LabProgram
7: Write a program that reads a line
of integers, then displays each integers and the sum of all the integers
import
javax.swing.JOptionPane;
import
java.util.*;
class
lab7
{
public static void main(String[]
args)
{
//String s=new
String("4$8$9$67");
//StringTokenizer t=new
StringTokenizer(s,"$");
String s;
s=JOptionPane.showInputDialog("Enter
the string");
StringTokenizer t=new
StringTokenizer(s,"$");
int a,sum=0;
System.out.println(t.countTokens());
while(t.hasMoreTokens())
{
a=Integer.parseInt(t.nextToken());
System.out.println(a);
sum=sum+a;
}
System.out.println("Total="+sum);
}
}
LabProgram
4: Write a program to check whether a given string is palindrome or not.
import
javax.swing.JOptionPane;
class
lab4
{
public static void main(String[]
args)
{
String s;
s=JOptionPane.showInputDialog("Enter
a String");
char
ch[]=s.toCharArray();
int i,j,count=0;
for(i=0,j=ch.length-1;i<j;i++,j--)
{
if(ch[i]!=ch[j])
{
System.out.println("Not
polindrome");
count=1;
break;
}
}
if(count==0)
System.out.println("Polindrome");
}
}
No comments:
Post a Comment