Activites Stringbuilder

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Activities -Stringbuilder

Student’s Name:

1. Show what is printed by the following section of code:

String str = "another value";


StringBuilder p = new StringBuiulder(str);
Your answer
p.delete(3,7);
System.out.println("p is: " + p); output: ano value
p.insert(4,"done");
System.out.println("p is: " + p); Output: anotdoneher value
p.replace(1,3,"XY");
System.out.println("p is: " + p); Output: aXYther value
2. For each of the following, show the result of the method call. For each part, start from the
following declaration and initial values:

StringBuilder str = new StringBuilder("your cat is full of fur");


StringBuilder str1 = new StringBuilder("lunchtime aggravation");
StringBuilder str2 = new StringBuilder("half of the apple");
Your answer
(a) str.replace(5,8,"dog"); (a): your dog is full of fur
(b) str.replace(20,23,"food"); (b): your cat is full of food
(c) str1.replace(5,9,"room"); (c): lunchroom aggravation
(d) str2.replace(12,17,"orange"); (d): half of the orange

3.For each of the following, show what is printed. For each part, start from the following declaration
and initial values:

StringBuilder str = new StringBuilder("happy home appliances");


StringBuilder str1 = new StringBuilder("living room refrigerator");
StringBuilder str2 = new StringBuilder("microwave telephone");
StringBuilder str3;
Your answer
(a) str.delete(6,10);
str.insert(6,"workplace");
System.out.println(str); (a): happy workplace appliances

(b) str1.delete(0,11);
str1.insert(0,"office");
System.out.println(str1); (b): office refrigerator

(c) str2.delete(5,9);
str3 = str2.substring(10,15); //careful
str2.insert(5,str3);
str2.delete(15,20);
str2.insert(15,"vision");
System.out.println(str2); (c): microphone television

(d) str1.delete(14);
str1.insert(14,"treat");
System.out.println(str1); (d): living room retreat

4 In the following program, called ComputeResult, what is the value of result after each numbered line
executes?

(បើក Comment ម្តងមួយបន្ទា ត់ៗ)


public class ComputeResult {
public static void main(String[] args) {
String original = "beltei university";
StringBuilder result = new StringBuilder("hi");
int index = original.indexOf('i');

/*1*/ // result.setCharAt(0, original.charAt(0));


/*2*/ // result.setCharAt(1, original.charAt(original.length()-1));
/*3*/ // result.insert(1, original.charAt(4));
/*4*/ // result.append(original.substring(1,4));
/*5*/ // result.insert(3, (original.substring(index, index+2) + " "));

System.out.println(result);
}
}
Your answer:
1) bi
2) by
3) bey
4) beyelt
5) beyi elt

You might also like