[Go to site: main page, start]

0% found this document useful (0 votes)
2 views49 pages

Adv Java Module2ppt

Uploaded by

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

Adv Java Module2ppt

Uploaded by

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

ADVANCED

JAVA
BCS613D

- Dr. SANTOSH K C
ASSOCIATE PROFESSOR
Dept. of C S & E
BIET, DAVANGERE
MODULE-2
String Handling
• The String Constructors, String Length, Special String
Operations.
• Character Extraction, String Comparison.
• Searching Strings, Modifying a String.
• Data Conversion Using valueOf( ).
• Changing the Case of Characters Within a String.
• joining strings, Additional String Methods.
• StringBuffer , StringBuilder.
String
What is a String in Java?
In Java, a String is a sequence of characters (like "Hello" or "Java"). In
some programming languages, strings are stored as character arrays. But
in Java, a String is an object of the String class.
Because strings are objects, Java provides many built-in methods to work
with them easily, such as:
■ Compare strings → equals()
■ Search a substring → contains(), indexOf()
■ Join strings → concat()
■ Change letter case → toUpperCase(), toLowerCase()
Example:
String s1 = "Hello";
String s2 = "World";
String s3 = [Link](s2); // HelloWorld
Package of String Classes
The following classes are in the [Link] package:
• String
• StringBuffer
• StringBuilder
■ Since [Link] is automatically imported, you do not need to
import them manually.
String Constructor
A constructor is a special method used to create and initialize an object.
The String class provides several constructors to create string objects in
different ways.

Types of String Constructors


1. Empty String Constructor
Creates a String with no characters (empty string).
Syntax:
String s = new String( );
Example:
String s = new String( );
[Link](s);
Output:

(The string is empty.)


2. String from Character Array
You can create a string using a character array.
Syntax:
String(char[ ] chars)
Example:
char[ ] chars = {'a','b','c'};
String s = new String(chars);
[Link](s);

Output:
■ abc Note: Characters in the array become
the string content.
3. String from Part of Character Array
You can create a string using only part of a character array.
Syntax:
String(char[ ] chars, int startIndex, int numChars)
Meaning:
• startIndex → starting position in array
• numChars → number of characters to use
Example:
■ char[] chars = {'a','b','c','d','e','f'};
String s = new String(chars, 2, 3);
[Link](s);
4. String from Another String
You can create a new string from an existing string object.
Syntax:
String(String strObj)
Example:
class MakeString {
public static void main(String[] args)
{
char[ ] c = {'J','a','v','a'};
String s1 = new String(c);
String s2 = new String(s1);
[Link](s1);
[Link](s2);
}
}

■ Output:
5. String from Byte Array
Java also provides constructors that create a String from a byte array.
Example:
byte[] b = {65,66,67};
String s = new String(b);
[Link](s);

Output:
■ ABC
String Length
The length of a string is the number of characters that it contains.
To obtain this value, call the length( ) method, shown here:
int length( )
Example:
char[ ] chars = { 'a', 'b', 'c' };
String s = new String(chars);
[Link]([Link]());

The above fragment prints "3", since there are three characters in the string s
Special String Operations
Java provides special support for string operations directly in the
language syntax to make programming easier.
Some common operations are:
1. String Literals
2. String Concatenation using +
3. Concatenation with other data types
1. String Literals
A string literal is a string written inside double quotes.
Example:
String s = "Hello";
Java automatically creates a String object for every string literal.
Example
char[ ] chars = {'a’, 'b’, 'c'};
String s1 = new String(chars);
String s2 = "abc";
Both create the same string "abc".
■ So instead of writing long code with new, programmers usually use string
literals.
2. String Concatenation
Java allows the + operator to join (concatenate) strings.
Example:
String age = "9";
String s = "He is " + age + " years old.";
[Link](s);

Output:
He is 9 years old.

■ The + operator combines multiple strings into one string.


3. Concatenation with Other Data Types
Java can concatenate strings with other data types like:
• int
• float
• double
• boolean
Example:
int age = 9;
String s = "He is " + age + " years old.";
[Link](s);
Output:
He is 9 years old.
■ Here Java automatically converts int to String before concatenation.
Character Extraction in Java
Character extraction means getting characters from a String.
Even though a String cannot be indexed like an array, Java
provides methods that allow us to access characters using indexes.
Just like arrays:
• Index starts at 0
Example string:
■ "JAVA"
0123
1. charAt( ) Method
This method returns a single character from a string.
Syntax
char charAt(int index)
• index → position of the character
Example
char ch;
ch = "abc".charAt(1);
[Link](ch);
Output
■ b
2. getChars( ) Method
This method copies multiple characters from a string into a character
array.
Syntax
void getChars(int sourceStart, int sourceEnd, char[] target, int targetStart)
Parameters
• sourceStart → starting index in string
• sourceEnd → ending index (not included)
• target → array where characters are stored
• targetStart → starting index in target array
Example
class getCharsDemo {
public static void main(String[] args) {

String s = "This is a demo of the getChars method.";

int start = 10;


int end = 14;

char[] buf = new char[end - start];


[Link](start, end, buf, 0);
[Link](buf);
}
}
Output
■ demo
3. toCharArray( ) Method
This method converts the entire string into a character array.
Syntax
char[ ] toCharArray( )
Example
String s = "Java";
char[] ch = [Link]();
for(char c : ch)
[Link](c + " ");

Output
■ Java
String Comparison
String comparison means checking whether two strings are the same
or different.
The String class provides several methods to compare strings.
The most commonly used methods are:
1. equals()
2. equalsIgnoreCase()
1. equals( ) Method
This method compares two strings character by character.
It returns:
• true → if both strings are exactly the same
• false → if they are different
■ Example:
String s1 = "Java";
String s2 = "Java";
String s3 = "JAVA";

[Link]([Link](s2));
[Link]([Link](s3));

2. equalsIgnoreCase() Method
regionMatches( ) Method
The regionMatches( ) method is used to compare a specific part (region) of one
string with a part of another string.
Syntax
■ boolean regionMatches(int startIndex, String str2,
int str2StartIndex, int numChars)
startsWith( ) Method
The startsWith( ) method checks whether a string begins with a specified
substring.
Syntax
boolean startsWith(String str)
Example
■ [Link]("Foobar".startsWith("Foo"));
Returns true
equals( ) vs ==

Example:
■ String s1 = new String("Java");
String s2 = new String("Java");
[Link](s1 == s2);

The == operator compares two object


references to see whether they refer to
the same instance.
Searching Strings
The String class provides methods to search characters or
substrings inside a string.
The two main methods are:
1. indexOf( ) – finds the first occurrence
2. lastIndexOf( ) – finds the last occurrence
Both methods return:
• Index position if found
• -1 if the character or substring is not found
Remember:
String indexing starts from 0
Example:
■ Java
0123
1. indexOf( ) Method
This method searches for the first occurrence of a character or substring.
Syntax (character)
int indexOf(int ch)
Example:
String s = "Java";
[Link]([Link]('a'));
Syntax (substring)
Output: 1
int indexOf(String str)
Because the first 'a' is at index 1.
Example:
String s = "Java Programming";
[Link]([Link]("Program"));

Output: 5
2. lastIndexOf( ) Method
This method searches for the last occurrence of a character
Syntax (character)
int lastIndexOf(int ch)
Example:
String s = "Java";
[Link]([Link]('a'));
Output 3
Syntax (substring)
Because the last 'a’ is at index 3.
int lastIndexOf(String str)
Example:
String s = "Java Programming Java";
[Link]([Link]("Java"));

Output 17
Modifying a String
In Java, String objects are immutable, which means:
• Once a string is created, its contents cannot be changed.
So when you modify a string:
• Java creates a new String object
• The original string remains unchanged
Example:
String s = "Java";
s = s + " Programming";
Here:
• "Java" is not modified.
• A new string "Java Programming" is created.
1. First Form of substring()
Syntax
String substring(int startIndex)
• startIndex → position where the substring begins
• The substring continues until the end of the string
Example
String s = "Programming";

[Link]([Link](3));
Output
■ gramming
2. Second Form of substring()
Syntax
String substring(int startIndex, int endIndex)
• startIndex → starting position
• endIndex → stopping position (not included)
Example
■ String s = "Programming";

[Link]([Link](3,7));
■ The following program uses substring( ) to replace all instances of one
substring with another within a string:
// Substring replacement.
class StringReplace {
public static void main(String[] args)
{
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
do { // replace all matching substrings [Link](org);
i = [Link](search);
if(i != -1) { result = [Link](0, i);
result = result + sub;
result = result + [Link](i + [Link]());
org = result; } }
while(i != -1);
}
}
■ Output:
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.
Data Conversion Using valueOf ( )
The valueOf( ) method is used to convert different types of data into a
String. It is a static method of the String class.
Because it is static, it is called like this:
[Link](data)
Purpose of valueOf( )
It converts internal data formats into human-readable string form.
Example:
• numbers → string
• objects → string
• character arrays → string
Example 1: Converting Numbers to String
public class ValueOfDemo {
public static void main(String[] args)
{
int num = 100;
String s = [Link](num);
[Link](s);
}
}
Output
■ 100
Here:
• integer 100 is converted into "100"
Example 2: Converting Double to String
double d = 10.5;

String s = [Link](d);
[Link](s);

Output
■ 10.5
Changing the Case of Characters Within a String
• The method toLowerCase( ) converts all the characters in a string from
uppercase to lowercase.
• The toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase.
• Nonalphabetical characters, such as digits, are unaffected.
Here are the simplest forms of these methods:
• String toLowerCase( )
• String toUpperCase( )
// Demonstrate toUpperCase() and toLowerCase().

class ChangeCase {
public static void main(String[] args)
{
String s = "This is a test.";
[Link]("Original: " + s);
String upper = [Link]();
String lower = [Link]();
[Link]("Uppercase: " + upper);
[Link]("Lowercase: " + lower);
}
}
Joining Strings
• The join( ) method is used to concatenate two or more strings, separating
each string with a delimiter, such as a space or a comma.
• It has two forms. Its first is shown here:
static String join(CharSequence delim, CharSequence . . . strs)
// Demonstrate the join() method defined by String.
class StringJoinDemo {
public static void main(String[] args) {
String result = [Link](" ", "Alpha", "Beta", "Gamma");
[Link](result);
result = [Link](", ", "John", "ID#: 569",
"E-mail: John@[Link]");
[Link](result);
}
}
StringBuffer
• StringBuffer supports a modifiable string.
• String represents fixed-length, immutable character sequences.
• In contrast, StringBuffer represents growable and writable character
sequences.

StringBuffer Constructors
StringBuffer defines these constructors:
■ StringBuffer( )
■ StringBuffer(int size)
■ StringBuffer(String str)
length( ) and capacity( )
The current length of a StringBuffer can be found via the length( ) method,
while the total allocated capacity can be found through the capacity( )
method.

They have the following general forms:


int length( )
int capacity( )
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer = " + sb);
[Link]("length = " + [Link]());
[Link]("capacity = " + [Link]());
}
}

Output: ???
charAt( ) and setCharAt( )
Accessing and Modifying Characters in StringBuffer
1. charAt( ) Method
The charAt( ) method is used to get a character from a specific position in
the StringBuffer.
Syntax
■ char charAt(int where)
2. setCharAt( ) Method
The setCharAt( ) method is used to change a character at a specific
position.
Syntax
■ void setCharAt(int where, char ch)
■ // Demonstrate charAt() and setCharAt().
class setCharAtDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer before = " + sb);
[Link]("charAt(1) before = " + [Link](1));
[Link](1, 'i’);
[Link](2);
[Link]("buffer after = " + sb);
[Link]("charAt(1) after = " + [Link](1));
}
}
OUTPUT: ????
insert( )
■ The insert( ) method inserts one string into another.
reverse( )
You can reverse the characters within a StringBuffer object using
reverse( ), shown here:
StringBuffer reverse( )
This method returns the reverse of the object on which it was called.
delete( ) and deleteCharAt( )
End of Module-02

- Dr. SANTOSH K C
ASSOCIATE PROFESSOR
Dept. of C S & E
BIET, DAVANGERE
Website: [Link]

You might also like