Chapter 6: Strings, I/O, Formatting, and Parsing Flashcards

1
Q
How many objects are created?
String s1 = new String("abc");
String s2 = s1;
String s2 = s1.concat("def");
A

3: abc, def and abcdef

Only two are still referenced abc and abcdef

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between:

String s1 = "abc"; // 1
String s2 = new String("abc"); // 2
A
  1. The string literal “abc” will go into the String literal pool and s1 will refer to it.
  2. A new object will be created in the normal memory pool, and s2 will refer to it. In addition the String literal “abc” will go into the String literal pool.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

String methods: Describe the method for getting a character from an specific index in a String.

A

public char charAt(int index)

Zero-based:
“MyString”.charAt(0); // returns ‘M’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

String methods: Describe the method for concatting a String.

A

public String concat(String s)

String test = “test”;
test.concat(“123”);
test + “123”;
test += “123”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

String methods: Describe the equals methods.

A

public boolean equals(String s)

public boolean equalsIgnoreCase(String s)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

String methods: Describe the method for retrieving the String size.

A

public int length();

“123”.length() // reeturns 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

String methods: Describe the method for replacing every occurance of a character in a String.

A

public String replace(char old, char new);

“xoxoxoxoxoxoxox”.replace(‘o’,’0’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

String methods: Describe the method for retrieving a part of a String.

A

public String substring(int begin)
public String substring(int begin, int end)

The begin argument is zero-based. The end argument is not zero based.

String s = “0123456789”;

s. substring(5); // 56789
s. substring(5, 8); // 567

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

String methods: Describe the mothods for lowercasing and upercasing.

A

public String toLowerCase();

public String toUpperCase();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

String methods: Describe the method for removing whitespace

A

public String trim();

” hello world “.trim(); // returns “hello world”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the differecence between the StringBuffer and StringBuilder classes?

A

StringBuffer is threadsafe, which means it’s methods are synchronized. StringBuilder is not threadsafe but is faster.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

StringBuffer/StringBuilder methods: Describe the method for appending.

A

public StringBuilder append(String s)

It can also take other arguments: boolean, char, double, float, int, long and others.

StringBuilder sb = new StringBuilder("test");
sb.append("123"); // sb is now test123
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

StringBuffer/StringBuilder methods: Describe the method for deleting a part of a String

A

public StringBuilder delete(int start, int end);

The start argument is zero-based the end argument is not zero-based.

StringBuilder sb = new StringBuilder("0123456789");
sb.delete(4,6); // sb is now 01236789
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

StringBuffer/StringBuilder methods: Describe the method for inserting a String.

A

public StringBuilder insert(int offset, String s)

The offset argument is zero-based. It can also take other arguments: boolean, char, double, float, int, long and others.

StringBuilder sb = new StringBuilder("01234567");
sb.insert(4, "---"); // sb is now "0123---4567
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

StringBuffer/StringBuilder methods: Describe the method for reversing a String.

A

public StringBuilder reverse();

StringBuilder sb = new StringBuilder("123");
sb.reverse(); // sb is now "321"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Describe the reader classes for File reading

A

FileReader
Used to read character files. Methods are fairly low level, allowing to read single characters, whole stream or a fixed number of characters.

BufferedReader
Used to make lower-level classes like FileReader easier to use. Keeps large chuncks of data in its buffer so file read operations are kept to a minimum.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Describe the writer classes for file writing

A

FileWriter
Used to write to character files. Methods are faily low level.

BufferedWriter
Used to make lower-level classes like FileWriter easier to use. Writes large chuncks of data at a time to keep write operations at a minimum.

PrintWriter
Easy write capabilities for files. Contains a set of handy methods and constructors (building a PrintWriter using a String or File).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you create a new (empty) file on disk?

How do you check if a file exists?

A
File file = new File("test.txt");
boolean exists = file.exists(); 
boolean newFileCreated = file.createNewFile();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What do the flush and close methods on the FileWriter class do?

A

Flush
Write the last data from the buffer to the file.

Close
Close the file and give back the resources to the system.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you write to a file using the FileWriter?

A
File file = new File("test.txt");
FileWriter fw = new FileWriter(file);
fw.write("testcontent");
fw.flush();
fw.close();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you read (to a char array) a file using a FileReader?

A
char[] contents = new char[50];
File file = new File("test.txt");
FileReader fr = new FileReader(file);
fr.read(contents);
fr.close();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are two ways to create actual files from Java?

A
  1. call the createNewFile() method on a File object.

2. Create a Writer or Stream: FileWriter, PrinterWriter or a FileOuputStream.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to create a new empty file in a new dir?

A

File dir = new File(“dir”);
dir.mkdir();
File file = new File(dir, “test.txt”);
file.createNewFile();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the result?

File dir = new File("dir");
File file = new File(dir, "test.txt");
file.createNewFile();
A

IOException!

Dir does not exist. Call mkdir(); first

25
Q

How can you list all the files in a folder?

A
File[] files = new File[50];
File dir = new File("dir");
files  = dir.list();
26
Q

What does System.console(); return?

A

Returns a Console object if ran in a console context (command line). Else null.

27
Q

What is the difference between the readLine and readPassword methods on the Console object?

A

readLine returns the String as inputed by the user. readPassword returns a char array, this way the users password wont remain in the String constant pool after validating it. Also the readPassword won’t echo the user input in the console.

28
Q

How to read a password from the Console?

A

Console c = System.console();

char[] pw = c.readPassword(“%s”, “Password: “);

29
Q

How to serialize a object to a file?

A

class Cat implements Serializable {}
Cat c = new Cat();
FileOutputStream fs = new FileOutputStream(“test.txt”);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();

30
Q

How to deserialize a object from a file?

A

class Cat implements Serializable {}
FileInputStream fs = new FileInputStream(“test.txt”);
ObjectInputStream os = new ObjectInputStream(fs);
Cat c = (Cat) os.readObject();
os.close();

31
Q

What does the transient keyword do?

A

Exclude particular fields from serialization.

32
Q

What does the interface Serializable do?

A

Marks an object as Serializable. If it has references to other objects that are not Serializable a NotSerializableException will be thrown when trying to serialize.

33
Q

What methods can be overriden to alter the way a object is read and written?

A

private void writeObject(ObjectOutputStream os);
private void readObject(ObjectInputStream is);

Inside these methods you can use the methods os.defaultWriteObject(); // for the default serialization
is.defaultReadObject(); // for the default deserialization

Also write and read extra object info:

os. writeInt(5);
is. readInt();

34
Q

What is the value of z, x and y after deserializing a Bar object?

class Foo {
   String z = "name";
}
class Bar extends Foo implements Serializable {
   transient int x = 42;
   transient Object y = new Object();
   public Bar(String s) {
      z = s;
   }
}
A

x and y will get their default values (0, null). When deserializing the constructor is not called and the instance variables don’t get their initial values. Also instance code blocks won’t run.

z will have its value “name”. Foo is not serializable so it constructor will run and the instance variables will get their initial value.

35
Q

How do you increment a Date object with a hour?

A
Date date = new Date();
date.setTime(date.getTime + 3600000);

Time is in milliseconds.

36
Q

What is the result?
Date date = new Date();
Calendar c = new Calendar();
c.setTime(date);

A

Compile error!

Calendar is an abstract class, use Calendar.getInstance();

37
Q

Using the Calendar class how do you add a day and subtract a year?

A

Calendar c = Calendar.getInstance();

c. setTime(new Date());
c. add(Calendar.DAY_OF_WEEK, 1);
c. add(Calendar.YEAR, -1);

38
Q

What is the result?
Current date = 1-12-2016

Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.roll(Calendar.MONTH, 2);
System.out.println(c.getTime());
A

1-2-2016

Roll increments without increasing bigger values (the year in this example) if needed.

39
Q

How to format and parse a date?

A
Date date = new Date();
DateFormat df = DateFormat.getDateFormat();
String formattedDate = df.format(date);
Date date2 = df.parse(formattedDate);
40
Q

What are the two constructors for the Locale class?

A

Locale(String language)
Locale(String language, String country)

ISO language code, ISO country code

41
Q

What is wrong?
Locale locale = new Locale(“nl”);
DateFormat df = DateFormat.getDateInstance();
df.setLocale(locale);

A

Compiler error!

Dateformat doesnt have an setLocale method. Locale should be provided during instantiation f.e.:
DateFormat.getDateInstance(DateFormat.LONG, locale);

42
Q

What are the two most important instance methods on the Local class?

A

getDisplayCountry(), getDisplayLanguage()

Optional Locale argument will return the display value in that locale.

43
Q

How to create a NumberFormat?

A

NumberFormat.getInstance();
NumberFormat.getCurrencyInstance();

Optional locale argument will return a NumberFormat using that locale.

44
Q

First parse a float to a string representation with 3 fraction digits. Then parse that String to integer only number.

float f1 = 123.456789f

A
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(3);
String s1 = nf.format(f1);
nf.setParseIntegerOnly(true);
float f2 = nf.parse(s1);
45
Q

What is the result?

Pattern p = Pattern.compile("aba");
Matcher m = p.matcher("abababa");
while(m.find()) {
    System.out.println(m.start() + " ")
}
A

0 4

2 does not match since it is already been used by the match starting at index 0.

46
Q

Describe the regex metacharacters.

A

\d digits
\s whitespace character
\w word character (letters, digits or underscore)

47
Q

Describe the regex pattern for:
a to z
a to z and A to C
a, e and F

A

[a-z]
[a-zA-C]
[aef]

48
Q

What does the +, *, ? do in regex?

A

+ Find atleast one or more occurences of the pattern
* Zero or more occurences of the pattern
? zero or one occurences of the pattern

49
Q

Create regex matching these 3:
1234567
123 4567
123-4567

A

\d\d\d[-\s]?\d\d\d\d

50
Q

What doest the . do in regex?

A

Match any character or whitespace, anything.

51
Q

what is the result:

source: yyxxxyxx
pattern1: .xx
pattern2: .
?xx

A
  • is greedy so it looks at the entire match to it wil only find one match at position 0 “yyxxxyxx”.
  • ? is not greedy (reluctant) it wil work from left to right and finds two matches: 0 “yyxx” and 4 “xyxx”.
52
Q

how would this regex look like in java?

\d. (1 digit and a literal dot (not the any character metacharacter)).

A

”\d\.”

Needs to be escaped

53
Q

What is the result of tokens?
String s1 = “abc, def,,ghi”;
String[] tokens = s1.split(“,”);

A

“abc”
“ def”
“”
“ghi”

54
Q

What are the three important methods for tokenizing using a Scanner?

A

useDelimiter(String regex) // set the delimiter of the scanner, default a space.
nextXxx() // f.e. nextLong(); for every primitive except char. Also moves to the next token.
hasNextXxx() // f.e. nextDouble(); for every primitive except char.

55
Q

Describe the construction of format Strings

A

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

The values between [] are optional.
arg_index - an integer followed directly by a $
flags - one or more flags
width - the minimum number of characters to print.
precision - number of decimals to print
conversion character - one of the conversion characters.

56
Q

What are the format flags you need to know?

A
  • \ left justify this argument
    + \ include a sign (+ or -) with this argument
    0 \ pad this argument with zero’s
    , \ Use locale-specific grouping seperators
    ( \Enclose negative numbers in parantheses
57
Q

What are the format conversion characters?

A
b - boolean
c - char
d - integer
f - floating point
s - string
58
Q

What is the result?
int i1 = -123;
int i2 = 12345;

System.out.printf(“>%1$(7d%0,7d%+-7d%+-7d

A

1 > (123)<
2 >012,345<
3 >+12345 <
4 IllgealFormatException!