Strings
By: Dimple Bohra
Introduction
► String represent a sequence of characters.
► In JAVA, strings are class objects and
implemented using two classes :
❑ String
❑ StringBuffer
► A java string is not a character array and is
not NULL terminated.
Declaration and Creation of String
Syntax:
String stringname=new String(“hello”);
or
String s=“stringname”;
e.g.
String firstName=new String(“Sachin”);
or
String s=“Sachin”;
Example
class StringExample
{
public static void main(String args[])
{ Scanner sc=new Scanner([Link]);
String s1="java"; //creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example");//creating java string by new keyword
String s4=[Link]();//taking string from user
[Link](s1);
[Link](s2);
[Link](s3);
[Link](s4);
}}
String Arrays
Syntax:
String Arrayname[]=new String[size];
Example:
class StringArray
{
public static void main(String[] args)
{
String[] s1 = {“abc", “xyz", “pqr"};
int size = [Link];
for (int i=0; i<size; i++)
{ [Link](s1[i]); }
}
}
String methods
Method call Task performed
s2=[Link]; Convert the string to all lowercase
s2=[Link]; Convert the string to all uppercase
s2=[Link](‘x’,’y’); Replace all appearances of x with y
s2=[Link](); Remove white spaces at the beginning and end
of the string s1
[Link](s2); Return true if s1=s2
[Link](s2) Return true if s1=s2, ignoring the case of
characters
[Link]() Gives the length of s1
[Link](n) Gives n th character of s1
[Link](s2) Returns negative if s1<s2,positive if s1>s2 and
zero if s1=s2
[Link](s2) Concatenates s1 and s2
Contd…
[Link](n) Gives substring starting from nth character
[Link](n,m) Gives substring starting from nth character
up to mth(excluding m th character)
[Link]() Creates a string representation of object p
[Link](‘x’) Gives the position of the first occurrence of
‘x’ in the string s1
[Link](‘x’,n) Gives the position of of ‘x’ that occurs
after nth position in the string s1
[Link](variable) Converts the parameter value to string
representation(converts int, float etc into
string)
Example
class String_method
{
public static void main(String args[])
{
String s="Sachin";
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link](s); //Sachin (no change in original)
[Link]([Link](3));
String ss=”Virat Kohali“;
[Link]([Link]());
[Link]([Link](3)); contd…
Contd…
[Link]([Link](2,7));
[Link]([Link]('a'));
[Link]([Link]('a',7));
int a=10;
String s2=[Link](a);
[Link](s2+10);
String s1="Java is a programming language. Java is a platform.";
String replaceString=[Link](“Java",“Python");//replaces all occurrences of
"Java" to " Python "
[Link](replaceString);
[Link]("Hello".concat("World"));
[Link]("Hello".compareTo("World"));
}
}
Ouput
Question 3(a)
Write a program to find number of
uppercase, lowercase characters, blank
spaces, digits and special character from a
string.
Solution
import [Link].*;
class Count
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("enter the String");
String s=[Link]();
int i,digit=0,whitespace=0,sp=0,upperCase=0,lowerCase=0;
char ch;
int l=[Link]();
for(i=0;i<l;i++)
{
ch=[Link](i);
if ([Link](ch))
{ upperCase++; } contd…
Contd…
else if ([Link](ch)){ lowerCase++; }
else if([Link](ch))
digit++;
else if(ch==' ')
whitespace++;
else
sp++;
}
[Link]("no of Uppercase="+upperCase);
[Link]("no of Lowercase="+lowerCase);
[Link]("no of Digit="+digit);
[Link]("no of Spaces="+whitespace);
[Link]("no of Symbol="+sp);
}
}
String to
character
array
Question 2
WAP to display string between round
braces from the given string.
solution
import [Link].*;
class Testbraces
{
public static void main(String args[])
{
int index1=0,index2=0;
String S1="(";
String S2=")";
Scanner sc=new Scanner([Link]);
[Link]("enter the String");
String a=[Link]();
contd…
Contd…
if ([Link](S1))
{
index1 = [Link](S1);
}
if ([Link](S2))
{
index2 = [Link](S2);
}
if(index1<index2)
{
[Link]([Link](index1+1,index2));
}
}
}
StringBuffer Class
► StringBuffer is a peer class of String.
► While String creates strings of fixed length,
StringBuffer creates string of flexible length that can
be modified in terms of length and content.
► We can insert characters and substrings in the middle
of a string or append another string to the end.
► Syntax :
StringBuffer stringname=new StringBuffer(“string");
► E.g.
StringBuffer sb=new StringBuffer("Hello");
StringBuffer Method
Method Task
[Link](n,’x’) Modifies the nth character
with x
[Link](s2) Appends the string s2 to s1
at the end
[Link](n,s2) Insert the string s2 at the
position n of the string s1
[Link](n) If n>[Link]() zeros are
added to s1.(
[Link]() Reverses the sequence of
characters
Example
class StringBufferexp
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link]("Java");
[Link](sb);
[Link](3,'o');
[Link](sb);
[Link](7,"aa");
[Link](sb);
[Link](5);
[Link](sb);
}
}
StringBuilder Class
► StringBuilder in Java represents a mutable sequence of
characters. Since the String Class in Java creates an
immutable sequence of characters, the StringBuilder
class provides an alternative to String Class, as it
creates a mutable sequence of characters.
► However, the StringBuilder class differs from the
StringBuffer class on the basis of synchronization. The
StringBuilder class provides no guarantee of
synchronization whereas the StringBuffer class does.
StringBuffer StringBuilder
StringBuffer is present since early versions of Java. StringBuilder was introduced in Java 5 (JDK 1.5).
StringBuffer is synchronized. StringBuilder is asynchronized.
Due to synchronization, StringBuffer is called a thread Due to its asynchronous nature, StringBuilder is not a
safe class. thread safe class.
Due to synchronization, StringBuffer is lot slower than Since there is no preliminary check for multiple
StringBuilder. threads, StringBuilder is a lot faster than StringBuffer.
Use in single-threaded or non-concurrent
Use in multi-threaded environments.
environments.
Example of StringBuilder
{
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link](sb);
}
Output:
Hello World
String Vs StringBuffer Vs
StringBuilder
StringTokenizer
► The [Link] class allows you to break
a String into tokens. It is simple way to break a String. It
is a legacy class of Java.
Example of String Tokenizer
{
String str = "apple,banana,orange";
StringTokenizer st = new StringTokenizer(str, ",");
while ([Link]())
{
[Link]([Link]());
}
}
Output of this snippet:
apple
banana
orange
Difference between String,
StringBuffer, StringBuilder and
StringTokenizer
► String: Immutable and thread-safe; creates new
objects for modifications.
► StringBuffer: Mutable, thread-safe (synchronized),
slower for frequent modifications in single-threaded
contexts.
► StringBuilder: Mutable, not thread-safe, faster in
single-threaded environments.
► StringTokenizer: Utility for breaking a string into
tokens; it’s a legacy class. Newer alternatives like
[Link]() or [Link] are recommended for
tokenization.
Java String Constant Pool
► A Java String Pool is a place in heap memory where all
the strings defined in the program are stored.
► A separate place in a stack is there where the variable
storing the string is stored.
► Whenever we create a new string object, JVM checks
for the presence of the object in the String pool, If
String is available in the pool, the same object
reference is shared with the variable, else a new object
is created.
Difference between String constant
pool and Heap
Difference between String
constant pool and Heap
► One way to skip this memory allocation is to use
the new keyword while creating a new string object.
► The ‘new’ keyword forces a new instance to always be
created regardless of whether the same value was used
previously or not.
► Using ‘new’ forces the instance to be created in the
heap outside the string constant pool which is clear,
since caching and re-using of instances isn’t allowed
here.
Difference between String constant
pool and Heap
Expt 3(e)
Thank You !!!