Printed from

Java SCJP Certification (Chap 6) - Strings, I/O, Formatting, and Parsing

Front Back

What's the big different between StringBuilder and StringBuffer

StringBuilder isn't thread-safe so it's faster. StringBuffer and StringBuilder have EXACTLY THE SAME INTERFACE!

String x = ""hello ""; x.concat(""world""); System.out.println(x); What prints?

""hello "" Most (all?) methods called on a string to change that string create a new String object which must be assigned to a reference --- notice that the original reference points to the unchanged String.

String s1 = ""spring ""; String s2 = s1 + ""summer ""; s1.concat(""fall ""); s2.concat(s1); s1 += ""winter ""; System.out.println(s1 + "" "" + s2); What is the output? How many String objects were created prior to the println statement?

output: spring winter spring summer String objects created (8): 1: ""spring "" (s1) 2: ""summer "" (lost) 3: ""spring summer "" (s2) 4: ""fall "" (lost) 5: ""spring fall "" (lost) 6: ""spring summer spring "" (lost) 7: ""winter "" (lost) 8: ""spring winter "" (s1 ""spring "" now lost) Strings are immutable so they can't be updated. Instead when a string is ""updated"" - a brand new string is actually created.

String s1 = new String(""test""); String s2 = new String(""test""); How many string objects are created by this statement?

3. 1: the literal ""test"" gets turned into a String object and placed in the ""String constant pool"" 2: a new String object with the value ""test"" placed in the non-pool. 3: another new String object with the value ""test"" also placed in the non-pool.

String method - returns the character located at the specified index?

public char charAt(int index)

String method - appends one String to the end of another?

public String concat(String s)

String method - determine the equality of two Strings ignoring case?

public boolean equalsIgnoreCase(String s)

String method - returns the number of characters in the String?

public int length()

String method - swaps occurrences of some character with a new character?

public String replace(char old char new)

String method - returns part of a string?

public String substring(int begin) public String substring(int begin int end) NOTE: ""substring"" is all lower case NOTE: begin is inclusive and end is exclusive

String method - return string with uppercase converted to lowercase?

public String toLowerCase() NOTE: starts with ""to"" NOTE: IS camel cased!

String method - return string with lowercase converted to uppercase?

public String toUpperCase()

String method - return string with whitespaces removed from front AND end?

public String trim()

StringBuffer str = """"; What is wrong with this?

Only String objects use the shortcut of creation by assignement of a literal. To create a StringBuffer object you must explicitly build an object: new StringBuilder(""..."");

Name 2 big differences between a String and a StringBuffer

A String is immutable while a StringBuffer isn't - it can be changed. This leads to the second big difference. String methods do not change the original string and instead only return new strings. StringBuffer methods though do change the object on which the method is called. String s = ""test""; s = s.concat("" one""); // calling object unchanged. new String object is created and s now points at it. StringBuffer sb = ""test""; sb.append("" two""); // change calling object. sb still points at same object which has had it's contents changed

StringBuffer method - add to the end?

public synchronized StringBuffer append(String s) NOTE: Returns a reference to itself for chaining of calls. NOTE: StringBuilder method is same except it is NOT synchronized.

StringBuilder method - return with a substring removed?

public StringBuilder delete(int begin int end) NOTE: object itself is changed as with all StringBuilder/StringBuffer methods NOTE: begin is inclusive end is exclusive NOTE: there is no overloaded type with only a single begin argument

StringBuilder method - insert a string at a certain offset point?

public StringBuilder insert(int offset String s) NOTE: all insert methods require an offset NOTE: offset is inclusive NOTE: everything at and above insert point is moved over to make way for the inserted string

StringBuffer method - reverse contents?

public synchronized StringBuffer reverse()

What's the basic difference between InputStream/OutputStream and Reader/Writers?

Streams are about moving bytes while Reader/Writers are about moving characters.

What does the File class represent?

An abstract represenation of a file and directory pathnames.

What are FileReader/FileWriter used for?

Read and Write characters out of files.

Describe how BufferedReader/BufferedWriter are used.

Both take lower level Reader and Writer classes (i.e. FileReader & FileWriter) easier to manipulate. NOTE: BufferedWriter provides method: newLine() which allows for creation of platform specific line separators (newLine is camel cased) NOTE: BufferedReader has a readLine() method (readLine is camel cased)


Enhanced in Java 5. In past could only construct with OutputStream or a Writer. As of 1.5 can also create with a File and String. close() flush() format() print() printf() println() write()

What package do you find java I/O in?*

File f = new File(""temp.txt""); If temp.txt doesn't exist is it created automatically?

No. Creating a File object is not the same as creating a file on disk. Simply creating a File has nothing to do with any existing (or not existing) file. You must MANIPULATE/USE the File object for actual files to be affected.

How do you check to see if a file exists?

File f = new File(""myfile.txt""); if (f.exists()) {}

How do you create a new file on disk?

File f = new File(""temp.txt""); try { f.createNewFile(); } catch (IOException e) {} NOTE: There are other classes that automatically create files as part of their object creation (i.e. BufferedReader / BufferedWriter) NOTE: return true if file doesn't exist and was created return false if already exists. NOTE: createNewFile()might throw an IOException as do most I/O operations.

What are the 3 key methods of the FileWriter?

close() flush() write()

What is the 1 key method of the FileReader?


What method does BufferedReader add to a Reader it wraps?

readLine(); NOTE: notice that camel case!

What are the key constructor argument types of a File?

(String) (String String) (File String)

What are the key constructor argument types of a FileWriter/FileReader?

File or String

How do you create a new directory?

File f = new File(""foo""); f.mkdir();

Assume temp.txt does not exist. File f = new File(""temp.txt""); FileWriter fw = new FileWriter(f); Compiles? Runs?

Yes and yes. temp.txt will actually be automatically created on disk when the FileWriter (or a FileReader) object is created.

File f1 = new File(""foo""); File f2 = new File(f1 ""foo""); f2.createNewFile(); Compiles? Runs?

Compiler error. The createNewFile() has to be wrapped in a try clause because IOException might be thrown. If it's wrapped thusly it will throw an IOException if the directory ""foo"" doesn't exist. If directory ""foo"" exists but the file ""foo"" doesn't it will create the file and return true.

Assume relative directory foo/foo doesn't exist. File f1 = new File(""foo/foo""); try{ f1.mkdir(); } catch (IOException e){} Compiles? Runs?

Yes and yes. Running does NOT mean the directory gets created though. If the first foo directory already exists then the second WILL get created and true is returned. If the first foo directory does NOT exist then the mkdir() method creates no directories and false is returned. An exception is NOT thrown! mkdir() can only create one directory at a time.

Assume directory foo does not exist nor does foo.txt FileWriter f = new FileWriter(""foo/foo.txt""); Compiles? Runs?

During runtime an IOException will be thrown because while FileWriter/FileReader can create files when their objects are created... they cannot also create directories. if foo directory did exist this would run w/out throwing an exception and the foo.txt would get automatically created.

How do you know when you're at the end of a file using a BufferedFileReader?

when readLine() returns null. NOTE: readLine is camel cased.

File dir = new File(""foo""); dir.mkdir(); File f = new File(""foo/temp.txt""); try{ f.createNewFile(); } catch(IOException e) {} dir.delete(); Compiles? Runs?

Yes and yes. A directory named ""foo"" is created on disk and then in that directory a file called temp.txt is also successfully created on disk. When an attempt to delete the directory is made it simply returns false because you cannot delete a non-empty directory. Notices that it does NOT throw an exception in this case.

How do you rename a File?

Use the renameTo(File f) method on the File you want to change.

What is the difference between these 2 declarations? How do they function differently? File f1 = new File(""foo"" ""temp.txt""); File f2 = new File(""foo/temp.txt"");

They are the same. They function exactly the same.

File dir = new File(""foo""); dir.mkdir(); File f = new File (""foo/stuff.txt""); try { f.createNewFile(); } catch (IOException e){} File dir2 = new File(""fee""); dir.renameTo(dir2); Compiles? Runs? Exception thrown?

It compiles runs and no exception is thrown (assuming system allows file creation) Directory foo gets created. Then stuff.txt gets put inside of it. Then directory foo simply gets renamed to fee -- it doesn't matter that foo had stuff in it. The is now no foo directory just a fee directory with a file called stuff.txt

How do you generate a list of all the files in directory?

File dir = new File(""foo""); []String files = dir.list();

What I/O streams are used to serialize and then unserialize objects? What methods are called to perform these serialization behaviors?

ObjectOutputStream.writeObject(); ObjectInputStream.readObject();

What argument does the ObjectOutputStream constructor include?

An OutputStream or no arguments(used by children of this class). There is not constructor that takes a File or a String.

What is definition of the interface used to serialize?

public interface Serializable{} NOTE: Serializable is a ""marker"" interface -- just marks any implementing objects as a certain kind of thing (in this case objects mark themselves as Serializable things)

What will you probably have to do after calling readObject() on an ObjectInputStream?

Cast the Object to it's actual class.

Does serialization make deep or shallow copies of everything it stores?

Deep. All the objects that the top level objects owns are (and that they then own and so on) are also serialized. Primitives are also serialized.

If a object marked Serializable owns an instance of another object type that is NOT serializable what happens when you call on writeObject() on the top level object?

Runtime error. NotSerializableException

How to you keep an instance variable from being serialized?

Use the transient modifier.

Give an example of why you'd want to keep an instance variable from being serialized along with it's owning object?

If that ivar is of a type that is not serializable a NotSerializableException will be thrown unless it's maked transient.

Let's say an object has to mark some of its ivars transient? How might it restore those ivars when it gets unserialized?

"An object marked Serializable can implement it's own special writeObject() and readObject() methods

"If a class is not marked Serializable

can it be serialized?"

"What must a Serializable object

which inherits from non-serializable classes

"If a class is not marked Serializable

can it be serialized?"

What must a Serializable object which inherits from non-serializable classes do to serialize without throwing runtime errors?

It's ivars might cause NotSerializableExceptions-s but it's ancestors will cause no problem. The first ancestor (and all ancestors above that) will simply be rebuilt by the calling of constructors. The values that come from these ancestor classes will be just as were at the point of the original object creation All classes that are serializable in the ancestral tree do NOT have their constructors called - and instead state is restored accordingly.

Which are marked serializable: the collection interfaces or the concrete collection classes?

The classes.

What must be true of an array and a collection before either can be serialized?

All their elements must be serializable.

What packages are Dates Numbers Currencies found in?

java.util.* -Date -Calendar -Locale java.text.* -DateFormat -NumberFormat

Get current date and time.

Date d = new Date(); System.out.println(d.toString()); OR Calendar c = Calendar.getInstance(); Date d = c.getTime(); System.out.println(d.toString());

Get an object that lets you perform date and time calculations in a different locale.

Locale l = new Locale(language); or Locale l = new Locale(language country); Calendar c = Calendar.getInstance(l); c.add(...) & c.roll(...) to add and subtract time to the existing date and time. c.set(...) & c.setTime(...) to set the date and time anew.

Get an object that lets you perform data and time calcs and then format it for output in different locales with different date styles.

Calendar c = Calendar.getInstance(); Locale l = new Locale(language); or Locale l = new Locale(language country); Date d = c.getTime(); DateFormat df = DateFormat.getInstance(style l); String s = df.format(d);

Get an object that lets you format numbers or currencies accross many different locales.

Locale l = new Locale(...); NumberFormat nf = NumberFormat.getInstance(l); or NumberFormat nf = NumberFormat.getCurrencyInstance(l); String s = nf.format(someNumber);

What's the relationship between the Date and Calendar classes?

Date has for the most part been depricated and replaced by Calendar. There are times when Date bridges gaps between Calendar and other classes (specifically DateFormat class)

What is notable about instantiating Calendar objects vs. Date objects?

While new Date() works fine Calendar is ABSTRACT! Thus you cannot directly create a Calendar object. You have to do it indirectly using a static method: Calendar c = Calendar.getInstance();

What does a Date represent?

The number of milliseconds(internally as a long) since January 1st 1970 12am. I sniff a unix timestamp! ;P

Besides toString() what are the 2 methods we want to know about in the Date class?

getTime() <-- returns milliseconds setTime(long milliseconds) NOTE: working in milliseconds scale and NOT the seconds scale! BTW: 1000 milliseconds = 1 second

What Calendar methods should you be familiar with?

Assume: Calendar c = Calendar.getInstance(); getTime(); // Returns a Date obj setTime(Date d); set(...); // numeric args to set up a date & time getFirstDayOfWeek() -returns value from Calendar.SUNDAY to Calendar.SATURDAY get(c.DAY_OF_WEEK) add(field amount) where field = Calendar.SECOND Calendar.MINUTE Calendar.HOUR Calendar.YEAR Calendar.DAY_OF_WEEK etc. roll() acts like add() except when a part of Date get incremented or decrmented larger parts of the Date will not change

What Class do you ideally use to create a date so that it can be manipulated?

Calendar Calendar c = Calendar.getInstance(); // date AND time Calendar c = Calendar.getDateInstance(); // date only

DateFormat df = new DateFormat(); Compiles? If not how would you make it compile?

Fails to compile. DateFormat is abstract. Need to call one of the following static methods: getInstance(); - unlike getDateInstance() includes time as well - is the default and uses a SHORT formatter for both date and time - a SHORT time formatter means that there will be no milliseconds getDateInstance(); getDateInstance(style); -where style is DateFormat.SHORT DateFormat.MEDIUM DateFormat.LONG DateFormat.FULL getDateInstance(field locale);

Methods of a DateFormat object?

getInstance() getDateInstance() getDateInstance(SHORT/MEDIUM/LONG/FULL) getDateInstance(SHORT/MEDIUM/LONG/FULL Locale) format(Date d) parse(String dateAsString) -might throw a ParseException!

How does Date connect Calendar and DateFormat?

DateFormat method format() does not take a Calendar object. It only takes a Date or in some cases a Number object. So if you convert your Calendar to a Date then you can use DateFormat.

What happens when you call Calendar's toString() method?

You get lots of crud! Better to output as a Date (getTime() will output Date object) and either use Date's toString() or use Date as argument of DateFormat's format() method.

When you send a bad string to a DateFormat object's parse() method what happens?

a CHECKED exception gets thrown (meaning you MUST do a parse inside a try block or declare that the current method throws the exception) This is what might be thrown: ParseException

Calendar c = Calendar.getInstance(); Date d = c.getTime(); System.out.println(d); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); String s = df.format(d); d = df.parse(s); System.out.println(d); Compile? If so will the printed outputs match?

This will NOT compile if if the DateFormat parse() method call is not inside a try statement or part of a method that declares it throws the checked ParseException. If the above condition is met then NO the 2 strings printed will not be the same (probably ;P ). When the Date is formatted with the DateFormat.SHORT field the formatted string doesn't include any time information. When that string get's parsed back into a Date object it now is missing any time info. So unless this code is run EXACTLY at midnight the 2 strings output will be different.

If the Locale class is abstract how do you instantiate a Locale object?

The Locale class IS NOT abstract (so you directly instantiate) new Locale(String language); new Locale(String language String country); ISO 639 = language codes ISO ? = country codes (you don't need to know any codes for the exam)

What happens when you try to format with a locale language or country that's not supported on the local machine? Compiles? Runs?

Yes and yes. But the output will be question marks. I.E. ?????? ?? ?????? ????

When you want to change locales in a DateFormat or NumberFormat object what method to you call on the formatting object?

None. You must create a new formatting object if you want to change locales. Once a formatting object is built with a Locale object that Locale object is immutably set.

What are the primary methods you'll call on a locale object?

Locale l1 = new Locale(String language String country); l1.getDisplayCountry(); or l1.getDisplayCountry(Locale l2) // The actual instace of the locale will be displayed in default locale format if no arg version called and will display in the locale format of the argument if a Locale argument is provided. l1.getDisplayLanguage() l1.getDisplayLanguage(Locale l2)

How do you get an instance of the NumberFormat class?

NumberFormat.getInstance(); NumberFormat.getInstance(Locale l); NumberFormat.getNumberInstance(); NumberFormat.getNumberInstance(Locale l); NumberFormat.getCurrencyInstance(); NumberFormat.getCurrencyInstance(Locale l);

What are the important methods of the NumberFormat class?

NumberFormat nf = NumberFormat.getInstance(); nf.getMaximumFractionDigits() nf.setMaximumFractionDigits(int i) // fractions higher than max will be ROUNDED (not truncated) nf.setParseIntegerOnly(boolean b) - if set to true then any decimals in parse string when parse() converts a string to a primitive number nf.parse(String s) - throws ParseException nf.format(primitive number)

What package is regex found in?


How do you set up a pattern in Java's regex?

Pattern p = Pattern.compile(String s); NOTE: You don't directly instantiate a pattern object! Instead you call the static method compile(String s) which outputs a Pattern object

How do you build an object that looks for matches?

Pattern p = Pattern.compile(String lookForThis); Matcher m = p.matcher(String lookInHere);

How might you iterate through a source string to find all the matches of certain pattern?

Pattern p = Pattern.compile(""\\d*""); Matcher m = p.matcher(""123abc456def""); boolean b; System.out.println(p.pattern()); while (b = m.find()) { System.out.println(m.start() + "": "" +; }

In regex what do the following quantifiers mean? + ? *

+ = 1 or more occurrences ? = zero or 1 * = 0 or more

What are the 3 behavioral qualities of quantifiers in regex?

greedy (default) - eats entire source string and works backwards reluctant (add a ?) - eats as little of string as it can and works forward possessive (add a +) - eats entire string like greedy but it does not work backwards. EXAMPLES: Current REGEX is: .*foo // greedy quantifier Current INPUT is: xfooxxxxxxfoo I found the text ""xfooxxxxxxfoo"" starting at index 0 and ending at index 13. Current REGEX is: .*?foo // reluctant quantifier Current INPUT is: xfooxxxxxxfoo I found the text ""xfoo"" starting at index 0 and ending at index 4. I found the text ""xxxxxxfoo"" starting at index 4 and ending at index 13. Current REGEX is: .*+foo // possessive quantifier Current INPUT is: xfooxxxxxxfoo No match found.

String ps = ""\d\d""; String source = ""123cat346""; Pattern p = Pattern.compile(ps); Matcher m = p.matcher(source); boolean b; while (b = m.find()) { System.out.println(m.start()); } What prints?

Compiler error. Compiler will read \d as an illegal escape. String literal needs to be \\d\\d

Pattern p = Pattern.compile(""\\d*""); Matcher m = p.matcher(""123abc456def""); boolean b; System.out.println(p.pattern()); while (b = m.find()) { System.out.println(m.start() + "": "" +; } What prints?

\d* 0: 123 3: 4: 5: 6: 456 9: 10: 11: 12: NOTE: The star (""*"") is greedy AND it will match 0 characters. At the 4th index... it first eats entire string and works backwards. When it finally works back to the ""a"" and that doesn't match it DOES match on the empty string. If you changed the * to a + you'd get what you might expect from this: \d+ 0: 123 6: 456

What package is Scanner found in?


What does Scanner do?

It scans a File InputStream Readable ReadableByteChannel or String. Often used for tokenizing it's source.

How do you use Scanner for searching?

Scanner s = new Scanner(; String token = """"; do { token = s.findInLine(""a""); } while (token != null);

Name 2 classes you can use for tokenizing?

String and Scanner

What's special about the String classes split method?

It takes String that is a regex expression.

What's the drawback of tokenizing with String's split(String regexPattern)?

It tokenizes it's target all at once. You can't do stuff after finding each token.

What is Scanner's default delimiter?


List the Scanner methods you need to know():

findInLine(String regexPattern); hasNext() - see if there is another token present (often use this in while loop along with next() - outputs boolean value next() - outputs the next token hasNextInt() hasNextBoolean() hasNextFloat() etc. - is there another token of this particular type? nextInt() nextBoolean() nextFloat() etc.. - get next token a particular type useDelimiter(String regexPattern) NOTE: there is NO hasNextXxx() nextXxx() for type char.

What is the most important thing to remember about the relationship between method format() and printf()?

They are aliases of each other!

What class are methods format() an printf() a part of?

When embedding argument-specfic formatting data in a string what character must that data begin with?

% (percent sign)

What is the structure of a format string?

%[arg_index$][flags][width][.precision]conversion char

Is the argument index in a printf() formatting string zero based


What are the possible flags that can be put in a formatting string?

- left justify + include sign (+ or -) 0 padd this arg with zeros use locale specific separators ( enclose neg #s in paras

What is the width declartion in a formatting string?

The minimum number of charaters to print for the argument

What is the precision declartion in a formatting string?

When using floats indicate number of digits to print after decimal point

What are the conversion character codes in a formatting string?

b boolean c char s string (NOT short) d integer (NOT decimal) f float

System.out.format(""%d"" 12.3); Compiles?

Yes but you get a runtime error! 12.3 is more specific than integer (d)

What is notable about an transient object ivar that has been instantiated to some object by it's constructor then serialized then deserialized?

It's set to null... UNLESS 1) A custom writeObject(ObjectOutputStream os) and custom readObject(ObjectInputStream) have been added to the class and recreate the object or.... 2) The ivar is part of an ancestor of the actual serialized object at which point it will get recreated when the ancestor's constructor is called.

Class A implements Serializable {} Class B extends A{} Class C extends B implements Serializable {} When serializing an object of Class C will the ivars of class A be restored via serializiation or will they be initialized by the A() constructor?

They'll be initialized by the constructor. The key point is that at the very first ancestor that is NOT serializable all ancestors above it will have their constructors called - regardless of whether they're marked Serializable or not. NOTE: Think about the constructor chaining that occurs when an object is instantiated.

Are static variables serialized?


What characters does the \w metacharacter represent?

\w stands for Word characters. They include: letters numbers underscore

What class is the split() method associated with? What does split() return?

The String class. It returns an array of Strings. The argument to the string() method is a regex expression that serves to define the delimiter. The tokens are then put in the array.

What is the difference between a token and a delimiter?

Delimiters are seperators and the stuff between the separators are the tokens.

BufferedWriter bf = new BufferedWriter(""temp.txt""); Compiles?

No. A BufferedWriter is a decorator class that can only be instantiated by wrapping another Writer object. It cannot take a string and turn that directly into a BufferredWriter. Here is what would work: try { FileWriter fw = new FileWriter(""temp.txt""); BufferedWriter bf = new BufferedWriter(fw); } catch (IOException e) {}

Currency c = new Currency(); Compiles? Runs?

It doesn't compile. Currency does not have a public constructor. Currency objects are created using static mehtod (getInstance). Currency is a singleton.

NumberFormat nf = NumberFormat.getCurrencyInstance(); nf.parse(""1234""); Compiles? What kind of object does parse function produce?

It does not compile. The parse method can throw a CHECKED exception ParseException and needs to be wrapped accordingly. If wrapped so and the string is a valid number then the parse function outputs an object of class Number (NOT class String).

System.out.format(""%b"" 123); What prints?

true the boolean conversion char ""b"" returns true for any non null or non-boolean argument.

System.out.format(""%f"" 123); What prints?

Runtime error. int literals are not automatically promoted to floats.

String a = new String(""hello""); String b = a.toString(); System.out.println(a == b); What prints?

True. toString() called on a String object returns the calling object.