append(): This method is available in java.lang.StringBuffer class of Java.
Syntax:
StringBuffer java.lang.StringBuffer.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. The length of this sequence is increased by the value of end-start.
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:
StringBuffer str = new StringBuffer("Hello world")
CharSequence s = "Hello"
int start = 0
int end = 2
str.append(s,start,end) = > It returns Hello worldHe.
Approach 1: When no exceptions.
Java
public class AppendStringBufferCharsequencelen {public static void main(String[] args) {StringBuffer str = new StringBuffer("Hello world");// append the CharSequence offset valueCharSequence s = "Hello";int start = 0;int end = 2;str.append(s, start, end);System.out.println(str);}}
Output:
Hello worldHe
Approach 2: IndexOutOfBoundsException
Java
public class AppendStringBufferCharsequencelen {public static void main(String[] args) {StringBuffer str = new StringBuffer("Hello world");// append the CharSequence offset valueCharSequence s = "Hello";int start = 3;int end = 2;str.append(s, start, end);System.out.println(str);}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: start 3, 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.StringBuffer.append(StringBuffer.java:387)
No comments:
Post a Comment