Java - String Class
Strings, which are widely used in Java programming,
are a sequence of characters. In the Java
programming language, strings are objects.
The Java platform provides the String class to
create and manipulate strings.
Creating Strings
The most direct way to create a string is to write:
String str = "Hello world";
In this case, "Hello world" is a string literal—a series of characters
in your code that is enclosed in double quotes. Whenever it
encounters a string literal in your code, the compiler creates a
String object with its value—in this case, Hello world.
Differences between String and StringBuffer in Java
The String class is immutable, so that once it is
created a String object cannot be changed.
Main difference between String and StringBuffer is
String is immutable while StringBuffer is mutable
means you can modify a StringBuffer object once you
created it without creating any new object.
(1)
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
(2)
Char chars[]={’a’,’b’,’c’,’d’,’e’};
String s=new String{chars,2,3};
(3)
String str=new String(“hello”);
Methods Of String Class
(1) charAt()
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to
length() - 1.
Example
import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1;
char ch;
[Link]("Enter Any String");
str1=[Link]();
ch=[Link](2);
[Link](ch);
ch=[Link](4);
[Link](ch);
}
}
Output will be
Enter Any String
GRAPHIC
A
H
(2) equals()
public boolean equals(Object anObject)
This method compares this string to the specified object.
The result is true if and only if the argument is not null and
is a String object that represents the same sequence of
characters as this object.
Example
import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1;
String str2;
[Link]("Enter First String");
str1=[Link]();
[Link]("Enter Second String");
str2=[Link]();
if([Link](str2))
{
[Link]("string are equals");
}
else
{
[Link]("string are not equals");
}
}
}
Output will be
(1)
Enter First String
kukreti
Enter Second String
vedik
string are not equals
(2)
output will be
Enter First String
vedik
Enter Second String
VEDIK
string are not equals
(3) equalsIgnoreCase
public boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations. Two strings are
considered equal ignoring case if they are of the same length and corresponding
characters in the two strings are equal ignoring case.
Example
import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1;
String str2;
[Link]("Enter First String");
str1=[Link]();
[Link]("Enter Second String");
str2=[Link]();
if([Link](str2))
{
[Link]("string are equals");
}
else
{
[Link]("string are not equals");
}
}
}
Output will be
Enter First String
vedik
Enter Second String
VEDIK
string are equals
(4) public int length()
Returns the length of this string
Example
import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1;
int ln;
[Link]("Enter Any String");
str1=[Link]();
ln=[Link]();
[Link]("Length Of A String is "+ln);
}
}
Output will be
Enter Any String
Graphic Era University
Length Of A String is 22
(5) public char[] toCharArray()
Converts this string to a new character array.
Example
import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1;
[Link]("Enter Any String");
str1=[Link]();
char ch[]=[Link]();
for(int i=0;i<[Link];i++)
{
[Link](ch[i]);
}
}
}
Output will be
Enter Any String
KUKRETI
KUKRETI
(6) public String toLowerCase()
Converts all of the characters in this String to lower case
Example
import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1;
[Link]("Enter Any String");
str1=[Link]();
String str2=[Link]();
[Link](str2);
}
}
Output will be
Enter Any String
VEDIK
vedik
(7) public String toUpperCase()
Converts all of the characters in this String to upper case
Example
import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1;
[Link]("Enter Any String");
str1=[Link]();
String str2=[Link]();
[Link](str2);
}
}
Output will be
Enter Any String
kukreti
KUKRETI
(8) public String concat(String str)
Concatenates the specified string to the end of this string.
Example
import [Link].*;
public class Demo5
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1;
[Link]("Enter Any String");
str1=[Link]();
String str2=[Link](" welcome to java programming");
[Link](str2);
}
}
Output will be
Enter Any String
Hello
Hello welcome to java programming
(9) public String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.
Example1
public class Demo5
{
public static void main(String st[])
{
String str1="welcome to java programming";
String str2=[Link]('a','t');
[Link](str2);
}
Output will be
welcome to jtvt progrtmming
Example2
public class Demo5
{
public static void main(String st[])
{
String str1="welcome to c++ programming";
String str2=[Link]("c++","java");
[Link](str2);
}
Output will be
welcome to java programming
(10) public boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
Example
public class Demo99 {
public static void main(String[] args)
{
String str="Welcome To Java Program";
if([Link]("gram"))
[Link]("Valid");
else
[Link]("InValid");
}
}
Output will be
Valid
(11) public boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
Example
public class Demo99 {
public static void main(String[] args)
{
String str="Welcome To Java Program";
if([Link]("Wel"))
[Link]("Valid");
else
[Link]("InValid");
}
}
Output will be
Valid
(12) public int indexOf(ch)
Returns the index within this string of the first occurrence of the specified
character.
if no such character occurs in this string, then -1 is returned.
public class Demo99 {
public static void main(String[] args)
{
String s1 = "vedik kukreti";
int i = [Link]("k");
while(i != -1)
{
[Link](i);
i = [Link]("k",i+1);
}
}
}
Output will be
4
6
8
(13) public int lastIndexOf(ch)
Returns the index within this string of the last occurrence
of the specified character.
Example
public class Demo99 {
public static void main(String[] args)
{
String str="Welcome To Java Program";
int p=[Link]("o");
[Link](“Position Found = “+p);
}
}
Output will be
Position Found = 18
(14) public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Copies characters from this string into the destination character array.
srcBegin - index of the first character in the string to copy.
srcEnd - index after the last character in the string to copy. Src-end
dst - the destination array.
dstBegin - the start offset in the destination array.
String Str1 = new String("Welcome to Tutorial");
int ln=9-2;
char[] Str2 = new char[ln];
[Link](2, 9,Str2, 0);
[Link](Str2);
OutPut Will Be
lcome t
(15)public int compareTo(String anotherString)
Two String can be compared in java with compareTo() method. CompareTo()
method returns integer value. This value can be 0 when exactly matched two
strings with each others, otherwise it will return in negative and positive value of
integer.
the value 0 if the argument string is equal to this string; a value less than 0 if this
string is lexicographically less than the string argument; and a value greater than 0
if this string is lexicographically greater than the string argument.
Example1
import [Link].*;
public class Demo101
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1,str2;
[Link]("Enter String1");
str1=[Link]();
[Link]("Enter String2");
str2=[Link]();
if([Link](str2)==0)
{
[Link]("Both are Equals");
}
else
{
[Link]("Both String are not Equals");
}
}
}
Example2
import [Link].*;
public class Demo101
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
String str1,str2;
[Link]("Enter String1");
str1=[Link]();
[Link]("Enter String2");
str2=[Link]();
if([Link](str2)>0)
{
[Link]("String One is Greater");
}
else
{
[Link]("String two is Greater");
}
}
}
Example3
public class Demo99 {
public static void main(String[] args)
{
String str[] ={"one","two","abc","doc","bob"};
String temp;
int i;
for(i=0;i<[Link];i++)
{
for(int j=i+1;j<[Link];j++)
{
if(str[j].compareTo(str[i])<0)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
}
for(i=0;i<[Link];i++)
{
[Link](str[i]);
}
}
}
import [Link].*;
public class Demo99 {
public static void main(String[] args)
{
Scanner sr=new Scanner([Link]);
String str1;
String str2;
[Link]("Enter First String");
str1=[Link]();
[Link]("Enter Second String");
str2=[Link]();
if([Link](str2)==0)
{
[Link]("string are equals");
}
else if([Link](str2)<0)
{
[Link]("str1 is Less Than str2 ");
}
else
{
[Link]("str1 is Greater Than str2");
}
}
}
Output Will Be
Enter First String
Univers
Enter Second String
Graphic
str1 is Greater Than str2
Output Will Be
Enter First String
Graphic
Enter Second String
Univers
str1 is Less Than str2
Output Will Be
Enter First String
Kukreti
Enter Second String
Kukreti
string are equals
(16) int compareToIgnoreCase(String str)
This method compares two strings lexicographically,
ignoring case differences
Return Value:
This method returns a negative integer, zero, or a positive integer as the
specified String is greater than, equal to, or less than this String, ignoring
case considerations.
(17) String substring(int startindex)
This method has two variants and returns a new string that is a
substring of this string. The substring begins with the character
at the specified index and extends to the end of this string.
Syntax :
public String substring(int begIndex)
Parameters :
begIndex : the begin index, inclusive.
Return Value :
The specified substring.
String str="Welcome";
String temp=[Link](2);
[Link](temp);
Output will Be
Lcome
String substring(int startindex,int endindex)
This method has two variants and returns a new string that is a
substring of this string. The substring begins with the character
at the specified index and extends to the end of this string or
up to endIndex – 1, if the second argument is given.
Syntax :
public String substring(int begIndex, int
endIndex)
Parameters :
beginIndex : the begin index, inclusive.
endIndex : the end index, exclusive.
Return Value :
The specified substring.
String str="Welcome";
String temp=[Link](2,4);
[Link](temp);
Output will Be
Lc
Program to count Number of words
in a given string
public class Demo99 {
public static void main(String[] args)
{
String str = " vedik dfd kukreti dsfgsdg vxvxcv ";
int i,ln,word=1;
char ch,ch1;
str=[Link]();
ln=[Link]();
ln--;
for(i=0;i<[Link]();i++)
{
ch=[Link](i);
if(i==ln)
{
ch1=[Link](i);
}
else
{
ch1=[Link](i+1);
}
if(ch==' '&&ch1!=' ')
{
word++;
}
}
[Link](word);
}
}
(18) split() method
The string split() method breaks a given string around
matches of the given regular expression.
import [Link].*;
public class Myprog4
{
public static void main(String[] args)
{
String str = "one-two-three";
String[] temp;
temp = [Link]("-");
for(int i =0; i < [Link] ; i++)
[Link](temp[i]);
}
(19) public String trim()
This method returns a copy of the string, with leading
and trailing whitespace omitted.
import [Link].*;
public class Myprog4
{
public static void main(String[] args)
{
String str = " one two three ";
String strTrimmed = [Link]();
[Link]("Original String is: " + str);
[Link]("New String is: " + strTrimmed);
Output is
Original String is: one two three
New String is: one two three
(20) String regionMatches() Method
public boolean regionMatches(int toffset,
String other,
int ooffset,
int len)
Parameters
Here is the detail of parameters −
toffset − the starting offset of the subregion in this string.
other − the string argument.
ooffset − the starting offset of the subregion in the string argument.
len − the number of characters to compare.
Return Value
It returns true if the specified subregion of this string matches the
specified subregion of the string argument; false otherwise. Whether the
matching is exact or case insensitive depends on the ignoreCase
argument.
import [Link].*;
public class Test {
public static void main(String args[]) {
String Str1 = new String("Welcome to
javaprogramming");
String Str2 = new String("java");
[Link]("Return Value :" );
[Link]([Link](11, Str2, 0,
4));
Output
Return Value :true
equals() versus ==
It is important to understand that the equals( ) method and the == operator
perform two different operations. As just explained, the equals( ) method
compares the characters inside a String object. The == operator compares
two object references to see whether they refer to the same instance.
// equals() vs ==
Example1
public class Demo88
{
public static void main(String[] args)
{
String s1 = new String("Hello");
String s2 = new String("Hello");
[Link]([Link](s2));
[Link](s1 == s2);
Output will be
True
false
Example2
public class Demo88
{
public static void main(String[] args)
{
String s1 = new String("Hello");
String s2 = s1;
[Link]([Link](s2));
[Link](s1 == s2);
Output will be
True
True
StringBuffer class
String class represents fixed-length, immutable character
sequences. In contrast, StringBuffer represents growable and
writeable character sequences. StringBuffer may have
characters and substrings inserted in the middle or appended
to the end. StringBuffer will automatically grow to make room
for such additions and often has more characters preallocated
than are actually needed, to allow room for growth.
Differences between String and StringBuffer in Java
Main difference between String and StringBuffer is
String is immutable while StringBuffer is mutable
means you can modify a StringBuffer object once you
created it without creating any new object.
The String class is immutable, so that once it is
created a String object cannot be changed. If there
is a necessity to make a lot of modifications to
Strings of characters then you should use String
Buffer & String Builder Classes.
(1) StringBuffer str=new StringBuffer(“hello”);
(2) Scanner sr=new Scanner([Link]);
StringBuffer str=new StringBuffer();
[Link]([Link]());
[Link](str);
(3) String str=”hello”;
StringBuffer strbuff=new StringBuffer(str);
Methods of StringBuffer class
(1) append()
This method updates the value of the object that invoked the method. The
method takes boolean, char, int, long, Strings etc.
public StringBuffer append(boolean b)
public StringBuffer append(char c)
public StringBuffer append(char[] str)
public StringBuffer append(double d)
public StringBuffer append(float f)
public StringBuffer append(int i)
public StringBuffer append(long l)
public StringBuffer append(Object obj)
public StringBuffer append(StringBuffer sb)
public StringBuffer append(String str)
Example1
public class Demo88
{
public static void main(String[] args)
{
StringBuffer s1 =new StringBuffer("Hello EveryBody");
[Link]("welcome to java");
[Link](s1);
}
Example2
StringBuffer s1 =new StringBuffer("Hello EveryBody");
[Link](55.68);
[Link](s1);
Example3
Enter Data from user
import [Link].*;
public class Myprog4
{
public static void main(String st[])
{
Scanner sr=new Scanner([Link]);
[Link]("Enter Any String ");
StringBuffer str=new StringBuffer();
[Link]([Link]());
[Link](str);
}
}
=============================================================
(2)
public StringBuffer delete(int start,int end)
Removes the characters in a substring of this sequence. The substring
begins at the specified start and extends to the character at index end -
1 or to the end of the sequence if no such character exists. If start is
equal to end, no changes are made.
Parameters:
start - The beginning index, inclusive.
end - The ending index, exclusive.
Example1
public class Demo88
{
public static void main(String[] args)
{
StringBuffer s1 =new StringBuffer("HelloEveryBody");
[Link](2,5);
[Link](s1);
}
Output will be
HeEveryBody
Example2
StringBuffer s1 =new StringBuffer("HelloEveryBody");
[Link](2,16);
[Link](s1);
Output will be
He
(3)
public StringBuffer insert(int offset, String str)
Inserts the string into this character sequence.
The characters of the String argument are inserted, in order, into this
sequence at the indicated offset, moving up any characters originally
above that position and increasing the length of this sequence by the
length of the argument.
Example1
public class Demo88
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("hello Body");
[Link](6,"Every");
[Link](s1);
}
}
Output will be
hello EveryBody
Example2
StringBuffer s1 = new StringBuffer("hello Body");
[Link](6,55.68);
[Link](s1);
Output will be
hello 55.68Body
(4)
public StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters
in the specified String.
Parameters:
start - The beginning index, inclusive.
end - The ending index, exclusive.
str - String that will replace previous contents.
Example
public class Demo88
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("Hello EveryBody");
[Link](0, 5, "Welcome");
[Link](s1);
}
Output will be
Welcome EveryBody
(5)
public StringBuffer reverse()
This method reverses the value of the StringBuffer object that invoked the method.
Example
public class Demo88
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("Hello");
[Link]();
[Link](s1);
Output will be
olleH
(6)
public String toString()
Returns a string representing the data in this sequence.
compare StringBuffer
public class Demo88
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("Hello");
StringBuffer s2 = new StringBuffer("HelloEverybody");
String str1=[Link]();
String str2=[Link]();
if([Link](str2))
[Link]("Both string are equals");
else
[Link]("String are not equals");
}
Output
String are not equals
(7)
public int capacity()
Returns the current capacity. The capacity is the amount of storage
available for newly inserted characters, beyond which an allocation will
occur.
If We compare two object of StringBuffer
Class by using equals() method then
output will be
public class Myprog4
{
public static void main(String[] args)
{
StringBuffer s1 =new StringBuffer("Hello EveryBody");
StringBuffer s2 =new StringBuffer("Hello EveryBody");
if([Link](s2))
[Link]("Equals");
else
[Link]("Not Equals");
Output will be
Not Equals
If We want to compare value of two
StringBuffer Class object then program
will be
public class Myprog4
{
public static void main(String[] args)
{
StringBuffer s1 =new StringBuffer("Hello EveryBody");
StringBuffer s2 =new StringBuffer("Hello EveryBody");
String str1,str2;
str1=[Link]();
str2=[Link]();;
if([Link](str2))
[Link]("Equals");
else
[Link]("Not Equals");
-------------------------------------------------------------------------------------
Check for Palindrome
import [Link].*;
public class Demo88
{
public static void main(String[] args)
{
Scanner sr=new Scanner([Link]);
String str1;
[Link]("Enter String");
str1=[Link]();
StringBuffer s1 = new StringBuffer(str1);
[Link]();
String str2=[Link]();
if([Link](str2))
[Link]("Palindrome");
else
[Link]("Not Palinfrome");