Вы находитесь на странице: 1из 2

1.

What is the main difference between a String and a StringBuffer class?

String
String is immutable: you cant modify a string object but can replace it by creating a new instance. Creating a new instance is rather expensive.

StringBuffer/StringBuilder
StringBuffer is mutable: use StringBuffer or StringBuilder when you want to modify the contents. StringBuilder was added in Java 5 and it is identical in all respects to StringBuffer except that it is not synchronised, which makes it slightly faster at the cost of not being thread-safe. //More efficient version using mutable StringBuffer StringBuffer output = new StringBuffer(110); Output.append(Some text); for(int I =0; i<count; i++) { output.append(i); } return output.toString(); The above code creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer expands as needed, which is costly however, so it would be better to initilise the StringBuffer with the correct size from the start as shown.

//Inefficient version using immutable String String output = Some text Int count = 100; for(int I =0; i<count; i++) { output += i; } return output; The above code would build 99 new String objects, of which 98 would be thrown away immediately. Creating new objects is not efficient.

Another important point is that creation of extra strings is not limited to overloaded mathematical operators (+) but there are several methods like concat(), trim(), substring(), and replace() in String classes that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations, which offer better performance.

What is the difference between array length and string length? Arrays have an attribute(not method), called length strings have a method(not an attribute) called length(). 3. How do you perform date and time calculations and then format it for output in different locales and different date format styles? 1. Create a Calendar Calendar c= Calendar.getInstance(); 2. Create a Locale for each Location Locale loc= new Locale(...); 3. Convert Calendar to a date Date d=c.getTime(); 4. Create a DateFormat for each Locale DateFormat df=DateFormat.getDateInstance(style,loc); 5. Use the format() method to create formatted dates String s=df.format(d); 4. How do you get an object that lets you format numbers and currencies across many different locales? 1. Create Locale for each location Locale loc= new Locale(...); 2. Create NumberFormat NumberFormat nf=NumberFormat.getInstance(loc); //or NumberFormat nf=NumberFormat.getCurrencyInstance(loc); 3. Use format() to create formatted output
2.

String s=nf.format(someNumber);

Вам также может понравиться