130 likes | 278 Views
ICS3U – StringBuffer. Teacher: Mr. Ho Course URL: http://computerNHSS.wikispaces.com. Review of String. String is a special data type (or class) in Java E.g. String str1 = “Hello, I am a string”; Once str1 is assigned a value, its value cannot be changed. StringBuffer.
E N D
ICS3U – StringBuffer Teacher: Mr. Ho Course URL: http://computerNHSS.wikispaces.com
Review of String • String is a special data type (or class) in Java • E.g. String str1 = “Hello, I am a string”; • Once str1 is assigned a value, its value cannot be changed.
StringBuffer • Another special data type (or class) in Java • Like String, except that the value of StringBuffer can be changed.
Built-In Methods • StringBuffer sb = new StringBuffer(“Hello”); • sb.length(); // length of StringBuffer • sb.charAt(1); // getting a character • sb.insert(2, “ABC”); // inserting • sb.append(“DEF”); // appending • sb.reverse(); // reversing StringBuffer • String s = sb.toString(); // getting String
sb.length() In the main() method: StringBuffer sb = new StringBuffer(“Hello”); System.out.println(sb.length()); Output: 5
sb.charAt(1) In the main() method: StringBuffer sb = new StringBuffer(“Hello”); System.out.println(sb.charAt(1)); Output: e
sb.insert(2, “ABC”) In the main() method: StringBuffer sb = new StringBuffer(“Hello”); System.out.println(sb.insert(2, “ABC”)); Output: HeABCllo
sb.append(“DEF”) In the main() method: StringBuffer sb = new StringBuffer(“Hello”); System.out.println(sb.append(“DEF”)); Output: HelloDEF
sb.reverse() In the main() method: StringBuffer sb = new StringBuffer(“Hello”); System.out.println(sb.reverse()); Output: olleH
sb.toString() In the main() method: StringBuffer sb = new StringBuffer(“Hello”); String s = sb.toString(); System.out.println(s); Output: Hello
Classwork • Go to http://computerNHSS.wikispaces.com • Download the classwork: • JBB_pg_18.pdf • JBB_pg_19.pdf • JBB_pg_22.pdf