Page 322 - CITS - Computer Software Application -TT
P. 322
COMPUTER SOFTWARE APPLICATION - CITS
String formatted = String.format(“Hello, %s!”, “John”);
System.out.println(formatted); // Hello, John!
Example
public class FormatExample{
public static void main(String args[]){
String name=”Pradyumn”;
String sf1=String.format(“name is %s”,name);
String sf2=String.format(“value is %f”,32.33434);
//returns 12 char fractional part filling with 0
System.out.println(sf1);
System.out.println(sf2);
}
}
Output
name is Pradyumn
value is 32.334340
6 StringBuilder and StringBuffer
• For efficient string manipulation, especially when you need to concatenate strings in a loop or modify them
frequently, you can use the StringBuilder (not thread-safe) or StringBuffer (thread-safe) classes.
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(“Hello, “);
stringBuilder.append(“World!”);
String result = stringBuilder.toString();
Example
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer(“hello”);
buffer.append(“java”);
System.out.println(buffer);
}
}
Output
hellojava
309
CITS : IT&ITES - Computer Software Application - Lesson 78 - 84
78