Assignment_4: -Program on String and String Buffer.
Java - Strings Class
A Java String is an ordered, immutable sequence of characters. For example, "hello" or
"Java" are strings. Immutability means you cannot change a String object after you create it.
Java Strings allow you to work with text. You need them for user input, data storage, and
display.
How to Create Java Strings
You create Java Strings in two ways: using string literals or the new keyword.
1. Use String Literals
This is the most common way to create a String. Java treats text in double quotes as a String
literal.
An example:
String greeting = "Hello, World!";
Java stores String literals in the String Pool. This saves memory. If you create the same String
literal twice, Java points both variables to the same object in the pool.
2. Use the new Keyword
You can also create a String object using the new keyword. This creates a new String object
in the heap memory. This happens even if an identical String exists in the String Pool.
String name = new String("Alice");
Key Java String Methods
Java provides methods to work with Strings. These methods manipulate and analyze text.
In Java, a String represents a sequence of characters used for storing and manipulating
text. It is immutable and provides many built-in methods for operations like
concatenation, comparison, and manipulation.
public class StringMethod
public static void main(String[] args)
String str = "StringMethodforStringMethod";
[Link]("Length: " + [Link]());
[Link]("Uppercase: " + [Link]());
[Link]("Substring: " + [Link](2, 6));
Output
Length: 27
Uppercase: STRINGMETHODFORSTRINGMETHOD
Substring: ring
Commonly Used Java String Methods.
Java provides a rich set of String methods that help perform various operations like
comparison, searching, modification of string. Let's Understand one by one.
1. int length() Method
This method provides the total count of characters in the string.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]());
Output
13
2. charAt(int i) Method
This method returns the character at ith index.
public class StringMethod
{
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link](7));
Output
3. String substring(int i) Method
This method return the substring from the ith index character to end.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link](7));
Output
World!
4. String substring(int i, int j) Method
This method returns the substring from i to j-1 index.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link](7, 12));
Output
World
5. String concat( String str) Method
This method appends the given string to the end of the current string.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]("!!!"));
Output
Hello, World!!!!
6. int indexOf(String s) Method
This method returns the index within the string of the first occurrence of the
specified string. If the specified string s is not found in the input string, the method
returns -1 by default.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]("World"));
}
Output
7. int indexOf(String s, int i) Method
This method returns the index within the string of the first occurrence of the specified
string, starting at the specified index.
public class StringMethod
public static void main(String[] args)
String str = "Hello, World!";
[Link]([Link]("l", 4));
Output
10
8. int lastIndexOf(String s) Method
This method returns the index within the string of the last occurrence of the
specified string. If the specified string s is not found in the input string, the method
returns -1 by default.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]("l"));
Output
10
9. boolean equals(Object otherObj) Method
This method compares this string to the specified object.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]("Hello, World!"));
Output
true
10. boolean equalsIgnoreCase(String anotherString) Method
This method checks if two strings are equal, without considering letter case.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]("hello, world!"));
Output
true
11. int compareTo(String anotherString) Method
This method compares two string lexicographically.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]("Hello, Java!"));
Output
13
12. int compareToIgnoreCase(String anotherString) Method
This method compares two string lexicographically, ignoring case considerations.
public class StringMethod
public static void main(String[] args) {
String s = "Hello, World!";
[Link]([Link]("hello, java!"));
Output
13
13. String toLowerCase() Method
This method converts all the characters in the String to lower case.
public class StringMethod
public static void main(String[] args)
{
String s = "Hello, World!";
[Link]([Link]());
Output
hello, world!
14. String toUpperCase() Method
This method converts all the characters in the String to upper case.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]());
Output
HELLO, WORLD!
15. String trim() Method
This method returns the copy of the String, by removing whitespaces at both ends. It
does not modify the whitespace characters present between the text.
public class StringMethod
public static void main(String[] args)
String s = " Hello, Trim! ";
[Link]("'" + [Link]() + "'");
Output
'Hello, Trim!'
16. String replace(char oldChar, char newChar) Method
This method returns a new string where all instances of oldChar are replaced by
newChar.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]('l', 'x'));
Output
Hexxo, Worxd!
17. boolean contains(CharSequence sequence) Method
This method returns true if string contains the given string.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]("World"));
}
}
Output
true
18. char[] toCharArray() Method
This method converts the string into a new character array.
public class StringMethod
public static void main(String[] args)
String str = "Hello";
char[] chars = [Link]();
for(char c : chars)
[Link](c + " ");
Output
Hello
19. boolean startsWith(String prefix) Method
This method returns true if string starts with this prefix.
public class StringMethod
public static void main(String[] args)
String s = "Hello, World!";
[Link]([Link]("Hello"));
}
}
Output
true
StringBuffer Class
The Java StringBuffer class is mutable sequence of characters.
StringBuffer can be used to modify the content of a String with ease. It
provides many utility functions to manipulate a string. A StringBuffer
opearations are syncronized in nature and it is recommanded to be used in
multi-threading environment. In case, syncronization is not needed, we can go
for an alternate API StringBuffer.
StringBuffer Class methods
Following is the list of methods of the StringBuffer class. Each method is having multiple
examples to demonstrate the functionality of the method.
Method & Description
1. StringBuffer append()
This method appends the given string argument to the sequence.
2. StringBuffer appendCodePoint(int codePoint)
This method appends the string representation of the codePoint argument to this sequence.
3. int capacity()
This method returns the current capacity.
4. char charAt(int index)
This method returns the char value in this sequence at the specified index.
5. int codePointAt(int index)
This method returns the character (Unicode code point) at the specified index.
6. int codePointBefore(int index)
This method returns the character (Unicode code point) before the specified index.
7. int codePointCount(int beginIndex, int endIndex)
This method returns the number of Unicode code points in the specified text range of this
sequence.
8. StringBuffer delete(int start, int end)
This method removes the characters in a substring of this sequence.
9. StringBuffer deleteCharAt(int index)
This method removes the char at the specified position in this sequence.
10. void ensureCapacity(int minimumCapacity)
This method ensures that the capacity is at least equal to the specified minimum.
11. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
12. int indexOf(String str)
This method returns the index within this string of the first occurrence of the specified
substring.
13. StringBuffer insert()
This method inserts the string representation of the given argument into this sequence.
14. int lastIndexOf(String str)
This method returns the index within this string of the rightmost occurrence of the specified
substring.
15. int length()
This method returns the length (character count).
16. int offsetByCodePoints(int index, int codePointOffset)
This method returns the index within this sequence that is offset from the given index by
codePointOffset code points.
17. StringBuffer replace(int start, int end, String str)
This method replaces the characters in a substring of this sequence with characters in the
specified String.
18. StringBuffer reverse()
This method causes this character sequence to be replaced by the reverse of the sequence.
19. void setCharAt(int index, char ch)
Character at the specified index is set to ch.
20. void setLength(int newLength)
This method sets the length of the character sequence.
21. CharSequence subSequence(int start, int end)
This method returns a new character sequence that is a subsequence of this sequence.
22. String substring(int start)
This method returns a new String that contains a subsequence of characters currently
contained in this character sequence.
23. String toString()
This method returns a string representing the data in this sequence.
24. void trimToSize()
This method attempts to reduce storage used for the character sequence.
Methods inherited
This class inherits methods from the following classes −
[Link]
[Link]
Example: Append a Boolean to the StringBuffer
The following example shows the usage of Java StringBuffer
append(Boolean b) method. Here, we are instantiating a StringBuffer object
"buff" with the string name "tuts". Then, we invoke the append() method using
the "buff" object with a boolean argument "true". The return value will be the
appended string name "tuts true". Similarly, we demonstrate another case
using the string name "abcd" and a boolean argument "false".
public class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer stringBuffer = new StringBuffer("tuts ");
[Link]("buffer = " + stringBuffer);
// appends the boolean argument as string to the string stringBuffer
[Link](true);
// print the string stringBuffer after appending
[Link]("After append = " + stringBuffer);
stringBuffer = new StringBuffer("abcd ");
[Link]("stringBuffer = " + stringBuffer);
// appends the boolean argument as string to the string stringBuffer
[Link](false);
// print the string stringBuffer after appending
[Link]("After append = " + stringBuffer);
}
}
Output
buffer = tuts
After append = tuts true
stringBuffer = abcd
After append = abcd false