0% found this document useful (0 votes)
20 views24 pages

Part 4

The document provides an overview of the String class in Java, detailing its immutability, creation methods, and various operations such as concatenation and comparison. It also introduces the StringBuffer class, highlighting its mutability and methods for modifying string content. Additionally, the document covers the StringTokenizer class for parsing strings into tokens based on specified delimiters.

Uploaded by

ozrehan06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views24 pages

Part 4

The document provides an overview of the String class in Java, detailing its immutability, creation methods, and various operations such as concatenation and comparison. It also introduces the StringBuffer class, highlighting its mutability and methods for modifying string content. Additionally, the document covers the StringTokenizer class for parsing strings into tokens based on specified delimiters.

Uploaded by

ozrehan06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

16.

String Class
 String is a sequence of characters.
 But in Java, string is an object that represents a sequence of characters.
 The [Link] class is used to create a string object.
 String class provides methods to perform operations on string.
 In String class .equals() is used for content comparison

 A String object is created using


o By String Literal
Java String literal is created by using double quotes.
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in
the pool, a new string instance is created and placed in the pool.
String s1="Welcome";
String s2="Welcome"; //It doesn't create a new instance
Constructors of string class:-
1) String str=new String([Link]);
This constructor takes the String as a argument.
Ex:-
String str=new String(“vardhaman”);
[Link](str);//vardhaman
2) Stirng str=new String(char[]);
This constructor take the array of characters as a argument.
Ex:-
char ch[]={'a','b','c','d'};
String str1=new String(ch);
[Link](str1); //abcd
3) String str=new String(char[] ,int ,int );
This contructor takes the array of characters with starting index and ending index.
First int represent the starting position and Second int represent the ending position.
Ex:-
Char ch[]={'a','b','c','d'};
String str1=new String(ch,1,3);
[Link](str1);//bcd
class Test
{
public static void main(String[] args)
{
String str=“pavan”
[Link](str);
String str1=new String(“pavan”);
[Link](str1);
String str2=new String(str1);
[Link](str2);
char ch[]={‘p’,’a’,’v’,’a’,’n’};
String str3=new String(ch);
[Link](str3);
char ch1[]={'a',’p','a',’v','a','n','a'};
String str4=new String(ch1,1,5);
[Link](str4);
Byte b[]={65,66,67,68,69,70};
String str5=new String(b);
[Link](str5);
byte b1[]={65,66,67,68,69,70};
String str6=new String(b1,2,4);
[Link](str6);
}
}
 The Java String is immutable which means it
cannot be changed. Whenever we change any string,
a new instance is created.
 Immutable simply means unmodifiable or
unchangeable.
 Once string object is created its data or state
 can't be changed but a new string object is
created with changes.
class String1
{
public static void main(String args[])
{ Here Sachin is not changed but a new object is created
String s="Sachin"; with Sachin Tendulkar. That is why string is known as
[Link](" Tendulkar"); immutable.
[Link](s); // Sachin  As you can see in the above figure that two objects are
} created but s reference variable still refers to "Sachin" not
to "Sachin Tendulkar".
}
 But if we explicitly assign it to the reference variable, it
will refer to "Sachin Tendulkar" object.
class String1
{
public static void main(String args[])
{
String s="Sachin";
s= [Link](" Tendulkar");
[Link](s); // SachinTendulkar
}
}
Reason: Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers
to one object "sachin". If one reference variable changes the value of the object, it will be affected to all
the reference variables. That is why string objects are immutable in java.

 For mutable strings, we can use StringBuffer and StringBuilder classes.


//Converting String to particular type
public class Demo
{
public static void main(String[] args)
{
String str1= "27";
//convert string to int
int x = [Link](str1);
String str2= "345.67";
//convert string to double
double d = [Link](str2);
String str3="34.56";
//convert string to float
float f = [Link](str3);
String str4="4555526522426";
//convert string to long
long y= [Link](str4);
double res= (d*y+x) / f;
[Link]("The result is " +res);
}
}
//String Operations // Character Extraction
import [Link].*; //String s1 = "Welcome to Java String Methods";
public class StringOp1 char ch1 = [Link](3);
{ [Link](ch1);
public static void main(String[] args) char ch2[] = new char[5];
{ [Link](5,10,ch2,0);
// String length [Link](ch2); char ch3[ ] = new
String s1 = "Welcome to Java String Methods"; char[[Link]()];
[Link]("The no of characters are " + ch3 = [Link]();
[Link]()); [Link](ch3);
// String Concatenation // String Comparisons
int year = 2019; String s3 = new String("WELCOME");
String s2 = s1 + " " + year; String s4 = "WELCOME";
[Link](s2); String s5 = "welcome";
[Link](s2+2+2); [Link]([Link](s4)); //true
[Link](s2+(2+2)); [Link]([Link](s5)); //false
String str1= new String("Welcome"); [Link]([Link](s5));
String s = [Link](" to India"); //true
[Link](s);
String s6 = s3; //Modifying a string
[Link](s3==s4); //false String str11 = [Link](5);
[Link](s3==s6); //true String str22 = [Link](5, 15);
String s7 = "Food Time"; [Link](str11);
[Link]([Link]("Food")); //true [Link](str22);
[Link]([Link]("Time")); //true String str3 = [Link]("Strings");
[Link]([Link](s5)); //-ve value [Link](str3);
//Searching Strings String str4 =[Link]("Java" , "Advanced Java");
[Link]("The first occurance of l is " + [Link](str4);
[Link]('l')); String str5 = " Welcome ";
[Link]("The last occurance of l is " + [Link](str5);
[Link]('l')); [Link]([Link]());
[Link]("The first occurance of l is from 5 " + [Link]([Link]());
[Link]('l',5)); [Link]([Link]());
[Link]("The last occurance of l is from 5 " + String s11 ="";
[Link]('l',5)); [Link]([Link]());
[Link]("The first occurance of me is from 5 String s22 = "welcome to India with love";
" + [Link]("me",7)) String ss[ ] = [Link](" ");
[Link]("The last occurance of me is from 5 for(int i=0; i< [Link]; i++)
" + [Link]("me",7)); [Link](ss[i]);
}}
//Program to use split() (Even Words list)
import [Link].*;
public class Task
{
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a line of Text");
String line = [Link]();
String s[]= [Link](" ");
int count=0;
//for each loop
for(String word : s)
{
int len = [Link]();
if(len % 2 == 0)
{
count++;
[Link](word + " : " + len + " : " +count);
}
}
}
}
17. StringBuffer Class
• String Buffer is a class present in the [Link] package.
• StringBuffer is a final class so it can’t be inherited.
• StringBuffer is a mutable class so it is possible to change the content in the same location.
• StringBuffer .equals() method is used for reference comparison
Constructors of StringBuffer class
1) StringBuffer sb=new StringBuffer();
2) StringBuffer sb1=new StringBuffer(int capacity);
3) StringBuffer sb2=new StringBuffer(String str);
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default capacity 16
StringBuffer sb1=new StringBuffer(5);
[Link]([Link]());//your provided capacity
StringBuffer sb2=new StringBuffer(“vardhaman");
[Link]([Link]());//initial capacity+provided string length 24
[Link]([Link]()); //9
}
}
//Example-1
class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
//Example-2
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}
//Example-3 //Example-5
class Demo class Demo
{ {
public static void main(String args[]) public static void main(String args[]){
{ StringBuffer sb=new StringBuffer("Hello");
StringBuffer sb=new StringBuffer("Hello"); [Link]();
[Link](1,3,"Java"); [Link](sb);//prints olleH
[Link](sb);//prints HJavalo }}
} //Example-6
} class StringBufferExample6
//Example-4 {
class Demo public static void main(String args[])
{
{
StringBuffer sb=new StringBuffer();
public static void main(String args[]) [Link]([Link]());//default 16
{ [Link]("Hello");
StringBuffer sb=new StringBuffer("Hello"); [Link]([Link]());//now 16
[Link](1,3); [Link]("java is my favorite language");
[Link](sb);//prints Hlo [Link]([Link]());//now (16*2)+2=34 i.e
} (oldcapacity*2)+2
} }}
18. StringTokenizer class
A StringTokenizer in Java is a class that allows you to break a string into tokens or smaller parts based on a
specified delimiter.
It is part of the [Link] package and is particularly useful for parsing and processing text data.

Import the package: First, import the [Link] package at the beginning of your Java program to access
the StringTokenizer class.
Import [Link];

Create an instance of StringTokenizer: Instantiate a StringTokenizer object with the input string and the
delimiter you want to use. You can specify multiple delimiters if
needed.
String input = "This is a sample sentence, split into words";
StringTokenizer tokenizer = new StringTokenizer(input, " ,");
In this example, the space (" ") and comma (",") are used as delimiters.

Iterate through the tokens: You can use the hasMoreTokens() method to check if there are more tokens in the
string, and nextToken() to retrieve the next token.
while ([Link]()) {String token = [Link](); [Link](token);}
This loop will print each token (word) from the input string, split by the specified delimiters.
Optional: Customize the delimiter: You can also specify delimiters more flexibly by using the overloaded
constructor or the delimiterTokens() method to specify a pattern or regular expression as a delimiter.
Here's a complete example
import [Link];
public class StringTokenizerExample {
public static void main(String[] args) {
String input = "This is a sample sentence, split into words";
StringTokenizer tokenizer = new StringTokenizer(input, " ,");
while ([Link]()) {
String token = [Link]();
[Link](token);
}
}
}
When you run this program, it will tokenize the input string based on spaces and commas, producing the following output:
This
is
a
sample
sentence
split
into
//StringTokenizer Example
import [Link].*; while([Link]())
public class SumDemo {
{ String s = [Link]();
public static void main(String[] args) n=[Link](s);
{ [Link](n);
Scanner sc = new Scanner([Link]); sum=sum+n;
[Link]("Enter a line of Integers"); }
String str = [Link](); [Link]("Sum of Tokens is :"+sum);
StringTokenizer st=new StringTokenizer(str); [Link]("The Count of Tokens is "
[Link]("The Count of Tokens is " +[Link]());// 0
+[Link]()); }
int n,sum=0; }
[Link]("The tokens are");

You might also like