Module 3 Ajava
Module 3 Ajava
Module 3
String Handling
String Constructors in Java
The String class in Java provides several constructors to create strings from different types of
inputs. Here's an overview of these constructors and their usage:
1. Default Constructor
String s = new String();
Creates an empty String object with no characters.
2. Character Array Constructor
String(char chars[])
Initializes the String with the characters from the provided character array.
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars); // s = "abc"
3. Subrange of Character Array Constructor
String(char chars[], int startIndex, int numChars)
Initializes the String with a subrange of the provided character array.
startIndex specifies where the subrange begins, and numChars specifies the number of
characters to use.
Example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3); // s = "cde"
4. String Object Constructor
String(String strObj)
Initializes the String with the same sequence of characters as another String object.
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);
1
Advanced Java Programming 21CS642
2
Advanced Java Programming 21CS642
3
Advanced Java Programming 21CS642
Java provides several convenient operations for working with strings, including automatic
string creation from literals, concatenation, and conversion of other data types to strings.
Here’s a closer look at these special operations:
String Literals
In Java, you can create String objects either explicitly using the new operator or implicitly
using string literals.
1. Using String Literals: When you use a string literal, Java automatically creates a
String object. For example:
String s1 = new String("hello"); // Explicit creation
String s2 = "hello"; // Implicit creation using a string literal
Here, s2 is initialized directly with the string literal "hello". This is simpler and more efficient
than explicitly creating a String object using the new operator.
2. String Literal Example:
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars); // Explicit creation
String s2 = "abc"; // Implicit creation using a string literal
4
Advanced Java Programming 21CS642
In this example, the + operator is used to concatenate firstName, a space " ", and lastName
into the fullName string.
Conversion to String
Java provides several methods to convert other data types into strings. For example:
1. Using String.valueOf():
int number = 100;
String numberStr = String.valueOf(number);
System.out.println(numberStr); // Output: 100
String.valueOf() converts the integer 100 to its string representation "100".
2. Automatic Conversion with + Operator:
int age = 25;
String ageStr = "Age: " + age;
System.out.println(ageStr); // Output: Age: 25
Here, the + operator automatically converts the integer age to its string representation and
concatenates it with "Age: ".
String Concatenation with Other Data Types
In Java, string concatenation with other data types is straightforward and automatically
converts non-string operands into their string representations. Here's how it works:
Concatenating Strings with Other Data Types
When you concatenate a string with other data types, Java automatically converts the non-
string values into their string representations. For example:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s); // Output: He is 9 years old.
In this example, the integer age is converted to its string representation "9", and the resulting
string "He is 9 years old." is created.
Operator Precedence in Concatenation
Java follows operator precedence rules which can affect the result of string concatenation,
especially when mixed with other operations. Consider the following example:
String s = "four: " + 2 + 2;
System.out.println(s); // Output: four: 22
In this case, the concatenation is performed as follows:
5
Advanced Java Programming 21CS642
1. "four: " is concatenated with the string representation of the first 2, resulting in "four:
2".
2. "four: 2" is then concatenated with the string representation of the second 2, resulting
in "four: 22".
To ensure arithmetic operations are performed before concatenation, use parentheses:
String s = "four: " + (2 + 2);
System.out.println(s); // Output: four: 4
Here, 2 + 2 is evaluated first, giving 4, and then concatenated with "four: ".
String Conversion with toString()
When concatenating objects with strings, Java uses the toString() method to obtain their
string representations. Every class in Java inherits the toString() method from the Object
class, which you can override to provide meaningful descriptions of your objects.
1. Default toString() Method:
Object obj = new Object();
System.out.println(obj.toString()); // Output: java.lang.Object@<hashcode>
The default implementation of toString() provides the class name followed by the object's
hash code.
2. Overriding toString(): To provide a custom string representation, override the
toString() method in your class. For example:
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
@Override
public String toString() {
return "Dimensions are " + width + " by " + depth + " by " + height + ".";
6
Advanced Java Programming 21CS642
}
}
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
System.out.println(b); // Output: Dimensions are 10.0 by 14.0 by 12.0.
}
}
Character Extraction in Java
Java provides several methods for extracting characters from a String object. Here’s a
detailed look at the available methods:
1. charAt(int index)
The charAt() method is used to retrieve a single character from a specific index in the string.
The index is zero-based, meaning the first character is at index 0.
Syntax:
char charAt(int index)
index: The position of the character to retrieve.
Example:
String s = "abc";
char ch = s.charAt(1); // ch will be 'b'
System.out.println(ch); // Output: b
2. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
The getChars() method copies characters from a substring of the string into a specified
character array.
Syntax:
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
srcBegin: The starting index of the substring to copy.
srcEnd: The ending index (one past the end) of the substring.
dst: The destination character array.
dstBegin: The starting index in the destination array.
Example:
7
Advanced Java Programming 21CS642
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];
s.getChars(start, end, buf, 0);
System.out.println(buf); // Output: demo
}
}
3. getBytes()
The getBytes() method converts the string into an array of bytes using the platform’s default
character encoding.
Syntax:
byte[] getBytes()
Example:
String s = "hello";
byte[] bytes = s.getBytes();
System.out.println(Arrays.toString(bytes)); // Output might be [104, 101, 108, 108, 111] for
ASCII encoding
For specific character encodings, you can use:
byte[] getBytes(String charsetName)
Example:
byte[] bytes = s.getBytes("UTF-8");
4. toCharArray()
The toCharArray() method converts the entire string into a new character array.
Syntax:
char[] toCharArray()
Example:
String s = "hello";
char[] chars = s.toCharArray();
8
Advanced Java Programming 21CS642
9
Advanced Java Programming 21CS642
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
10
Advanced Java Programming 21CS642
System.out.println(starts);
System.out.println(ends);
System.out.println(startsFrom);
5. equals() vs ==
equals(): Compares the content of two String objects. It returns true if the strings have
the same sequence of characters.
==: Compares the references of two String objects to see if they point to the same
memory location.
Example:
class EqualsNotEqualTo {
public static void main(String[] args) {
String s1 = "Hello";
11
Advanced Java Programming 21CS642
12
Advanced Java Programming 21CS642
13
Advanced Java Programming 21CS642
}
}
Output:
-1
0
1
Sorting Strings with compareTo()
Here's an example that demonstrates sorting an array of strings using compareTo():
Bubble Sort Example:
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"
};
14
Advanced Java Programming 21CS642
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
15
Advanced Java Programming 21CS642
Example:
class IndexOfDemo {
public static void main(String[] args) {
String str = "Hello, world!";
System.out.println(str.indexOf('o')); // Output: 4
System.out.println(str.indexOf('o', 5)); // Output: 8
System.out.println(str.indexOf("world")); // Output: 7
System.out.println(str.indexOf("Java")); // Output: -1
}
}
2. lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified character or
substring within the invoking string. If the character or substring is not found, it returns -1.
Syntax:
int lastIndexOf(int ch)
int lastIndexOf(int ch, int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
int ch: The character to search for.
int fromIndex: The index from which to start the search, searching backwards.
String str: The substring to search for.
Example:
class LastIndexOfDemo {
public static void main(String[] args) {
String str = "Hello, world! Hello again!";
System.out.println(str.lastIndexOf('o')); // Output: 20
System.out.println(str.lastIndexOf('o', 10)); // Output: 4
System.out.println(str.lastIndexOf("Hello")); // Output: 13
System.out.println(str.lastIndexOf("Java")); // Output: -1
}
}
16
Advanced Java Programming 21CS642
3. contains()
The contains() method checks if the invoking string contains a specified substring. It returns
true if the substring is found, and false otherwise.
Syntax:
boolean contains(CharSequence sequence)
CharSequence sequence: The sequence of characters to search for.
Example:
class ContainsDemo {
public static void main(String[] args) {
String str = "Hello, world!";
System.out.println(str.contains("world")); // Output: true
System.out.println(str.contains("Java")); // Output: false
}
}
4. startsWith() and endsWith()
startsWith(String prefix): Checks if the invoking string starts with the specified
prefix. Returns true if it does, otherwise false.
endsWith(String suffix): Checks if the invoking string ends with the specified suffix.
Returns true if it does, otherwise false.
Syntax:
boolean startsWith(String prefix)
boolean startsWith(String prefix, int toffset)
boolean endsWith(String suffix)
String prefix: The prefix to check for.
String suffix: The suffix to check for.
int toffset: The index from which to start the search for the prefix.
Example:
class StartsEndsWithDemo {
public static void main(String[] args) {
String str = "Hello, world!";
System.out.println(str.startsWith("Hello")); // Output: true
17
Advanced Java Programming 21CS642
18
Advanced Java Programming 21CS642
19
Advanced Java Programming 21CS642
String s3 = s1 + "two";
System.out.println(s3); // Output: onetwo
}
}
3. replace()
The replace() method replaces occurrences of characters or character sequences.
Syntax:
String replace(char original, char replacement)
String replace(CharSequence target, CharSequence replacement)
Example:
class ReplaceDemo {
public static void main(String[] args) {
String str = "Hello";
String result = str.replace('l', 'w');
System.out.println(result); // Output: Hewwo
20
Advanced Java Programming 21CS642
21
Advanced Java Programming 21CS642
Method Signatures
Here are some common forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object obj)
static String valueOf(char[] chars)
For a subset of a char array:
static String valueOf(char[] chars, int startIndex, int numChars)
Example:
class ValueOfDemo {
public static void main(String[] args) {
double num = 123.45;
long lng = 9876543210L;
char[] chars = {'J', 'a', 'v', 'a'};
22
Advanced Java Programming 21CS642
String toUpperCase()
Example:
class ChangeCase {
public static void main(String[] args) {
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
23
Advanced Java Programming 21CS642
The StringBuffer class in Java provides a modifiable sequence of characters. Unlike the
String class, which represents immutable character sequences, StringBuffer allows characters
and substrings to be inserted or appended dynamically. This class is designed for creating and
manipulating strings that will change over time, providing efficient memory usage by pre-
allocating space for growth.
Constructors
StringBuffer has several constructors to initialize the buffer in different ways:
1. Default Constructor:
StringBuffer()
o Reserves room for 16 characters without reallocation.
2. Size Constructor:
StringBuffer(int size)
o Accepts an integer to set the initial size of the buffer.
3. String Constructor:
StringBuffer(String str)
o Initializes the buffer with a given string and reserves room for 16 additional
characters.
4. CharSequence Constructor:
StringBuffer(CharSequence chars)
o Initializes the buffer with the character sequence contained in chars and
reserves room for 16 more characters.
Methods
length() and capacity()
length(): Returns the current length of the character sequence.
int length()
capacity(): Returns the total allocated capacity of the buffer.
int capacity()
ensureCapacity()
Ensures that the buffer has a minimum capacity.
void ensureCapacity(int minCapacity)
setLength()
Sets the length of the character sequence, truncating or extending as necessary.
24
Advanced Java Programming 21CS642
25
Advanced Java Programming 21CS642
substring()
Extracts a substring from the buffer.
String substring(int start)
String substring(int start, int end)
Examples
StringBuffer length vs. capacity
class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
Output:
buffer = Hello
length = 5
capacity = 21
Using append()
class AppendDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
}
}
Hello World
Using insert()
class InsertDemo {
public static void main(String[] args) {
26
Advanced Java Programming 21CS642
27
Advanced Java Programming 21CS642
Using replace()
class ReplaceDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
Output:
After replace: This was a test.
Using substring()
class SubstringDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("This is a test.");
System.out.println(sb.substring(5));
System.out.println(sb.substring(5, 7));
}
}
Output:
is a test.
is
StringBuffer provides a versatile way to handle mutable strings in Java, offering methods to
modify, manipulate, and inspect character sequences efficiently.
28