Java - Instructor Insights
Our instructors have real-world experience in the technologies that they teach. Here they share their insights and discoveries on working with each of these technologies.
StringBuilder
Use StringBuilder rather than StringBuffer in your Java5+ implementations when you are writing single-threaded applications.
StringBuffer has long been used as a mutable alternative to String. It has traditionally been the recommended object to use whenever you want to modify a String's content.
public String getCompany() {
StringBuffer company= new StringBuffer();
company.append("Batky");
company.append("-");
company.append("Howell");
return company.toString();
}
Many of the methods in StringBuffer are synchronized. Synchronized methods provide protection against race conditions when used in a multi-threaded application. Synchronized methods are typically slower than their non- synchronized counterparts.
StringBuilder was added in Java5 to provide the mutable functionality of a StringBuffer without the added thread safety. For performance purposes, you should use a StringBuilder rather than a StringBuffer in single-threaded applications.
public String getCompany() {
StringBuilder company= new StringBuilder();
company.append("Batky");
company.append("-");
company.append("Howell");
return company.toString();
}
GregorianCalendar
Use the GregorianCalendar class instead of the Date class to represent dates in Java.
Dates in Java have been a source of confusion since Java 1.1. The class that you would expect to create new dates, java.util.Date, is not always the right choice. Using the no-arg Date constructor, you will get a Date object that represents the date and time when the object was created.
Date d = new Date();
All of the other constructors in Date have been deprecated.
If you want to create a new object that represents a particular point in time, use the constructors of the java.util.GregorianCalendar class, instead. GregorianCalendar extends java.util.Calendar. For example, the following code yields a Calendar object representing the day James Gosling was born.
Calendar cal = new GregorianCalendar(1955, Calendar.MAY, 19);
To create a Calendar object that represents the current date and time, use either the no-arg constructor of GregorianCalendar, or more simply, the static getInstance() method of Calendar.
Calendar now = Calendar.getInstance();
To print out a Calendar object, use the Java 5 System.out.printf() method:
System.out.printf("Gosling's Birthday: %1$tb %1$te, %1$tY", cal);
The "t" character indicates that we are doing a date/time conversion. The "b" character outputs the month as an abbreviation, the "e" character outputs the day of the month, and the "Y" outputs the four digit year. See java.util.Formatter for more information on date/time format strings.
|