append(): This method is available in java.lang.StringBuilder class of Java.
Syntax:
StringBuilder java.lang.StringBuilder.append(CharSequence s, int start, int end)
This method takes three arguments, one of type CharSequence and the other two are of type int as its parameters. This method appends a subsequence of the specified CharSequence to this sequence. Characters of the argument s, starting at index start, are appended, in order, to the contents of this sequence up to the (exclusive) index end.
Note:
1. The length of this sequence is increased by the value of end - start.
2. If s is null, then this method appends characters as if the s parameter was a sequence containing the four characters "null".
Parameters: Three parameters are required for this method.
s: the sequence to append.
start: the starting index of the subsequence to be appended.
end: the end index of the subsequence to be appended.
Returns: a reference to this object.
Throws:
IndexOutOfBoundsException - if start is negative, or start is greater than the end or end is greater than s.length().
For Example:
StringBuilder str = new StringBuilder("HELLO")
CharSequence cs = "WORLD"
int start = 0
int end = 2
str.append(cs, start, end) = > It returns HELLOWO.
Approach 1: When the index is in the range.
Java
public class AppendStringBuilderCharSequencelen {public static void main(String[] args) {StringBuilder str = new StringBuilder("HELLO");// append the CharSequence offset valueCharSequence cs = "WORLD";int start = 0;int end = 2;str.append(cs, start, end);System.out.println(str);}}
Output:
HELLOWO
Approach 2: When the index is out of range.
Java
public class AppendStringBuilderCharSequencelen {public static void main(String[] args) {StringBuilder str = new StringBuilder("HELLO");// append the CharSequence offset valueCharSequence cs = "WORLD";int start = -1;int end = 2;str.append(cs, start, end);System.out.println(str);}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: start -1, end 2, length 5 at java.base/java.lang.AbstractStringBuilder.checkRange(AbstractStringBuilder.java:1794) at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:675) at java.base/java.lang.StringBuilder.append(StringBuilder.java:212)
No comments:
Post a Comment