| 1. |
State the difference between String and StringBuffer. |
|
Answer» String objects in Java are immutable and final, so we can't change their value after they are created. Since STRINGS are commonly used in applications, we need to PERFORM several operations on them such as substring(), equals(), indexof(), toUppercase(), etc. Each time we manipulate a string, a new String object is created, and all PREVIOUS objects will be garbage, placing a strain on the garbage collector. This is why The Java team developed StringBuffer. A StringBuffer is a mutable object, meaning it can be changed, but the string is an immutable object, so it cannot be changed once it has been created.
Syntax: String str1="InterviewBit";String str2=new String("Scaler");Scanner str3=new Scanner(System.in);String str4=str3.nextLine();Example: Concatenation Example of String. A string class takes longer to perform a concatenation operation than a string buffer class. public class Scanner{ public STATIC void MAIN(String []args) { StringBuilder stbu=new StringBuilder(); //Initial object size System.out.println(stbu.capacity()); String str="Scaler"; System.out.println(str); String str1 = new String("InterviewBit"); System.out.println(str1); str1 += " Articles"; //string update System.out.println(str1); }}Output: 16ScalerInterviewBitInterviewBit Articles
Syntax: StringBuffer var = new StringBuffer(str);Example: Concatenation Example of StringBuffer. String buffer class perform concatenation operations more quickly than string classes. public class StringBuffer{ public static void main(String []args) { StringBuilder stbu=new StringBuilder(); //Initial object size System.out.println(stbu.capacity()); StringBuffer stbr= new StringBuffer("InterviewBit"); System.out.println(stbr); stbr.append(" Articles"); //string update System.out.println(stbr); stbr=new StringBuffer("Scaler"); System.out.println(stbr); }}Output: 16InterviewBitInterviewBit ArticlesScaler |
|