Showing posts with label String Handling. Show all posts
Showing posts with label String Handling. Show all posts
Friday, August 17, 2012
Exercise- 6 (Strings)
1. Given:
import java.util.regex.*;
class Regex2 {
public static void main(String[] args) {
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()) {
System.out.print(m.start() + m.group());
}
}
}
And the command line:
java Regex2 "\d*" ab34ef
What is the result?
A. 234
B. 334
C. 2334
D. 0123456
E. 01234456
F. 12334567
G. Compilation fails
Answer:
E is correct. The \d is looking for digits. The * is a quantifier that looks for 0 to many
occurrences of the pattern that precedes it. Because we specified *, the group() method
returns empty Strings until consecutive digits are found, so the only time group() returns
a value is when it returns 34 when the matcher finds digits starting in position 2. The
start() method returns the starting position of the previous match because, again,
we said find 0 to many occurrences.
A, B, C, D, F, and G are incorrect based on the above. (Objective 3.5)
A, B, C, D, F, and G are incorrect based on the above. (Objective 3.5)
2. Given:
import java.io.*;
class Player {
Player() { System.out.print("p"); }
}
class CardPlayer extends Player implements Serializable {
CardPlayer() { System.out.print("c"); }
public static void main(String[] args) {
CardPlayer c1 = new CardPlayer();
try {
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}
What is the result?
A. pc
B. pcc
C. pcp
D. pcpc
E. Compilation fails
F. An exception is thrown at runtime
Answer:
C is correct. It's okay for a class to implement Serializable even if its superclass doesn't.
However, when you deserialize such an object, the non-serializable superclass must run its
constructor. Remember, constructors don't run on deserialized classes that implement
Serializable.
A, B, D, E, and F are incorrect based on the above. (Objective 3.3)
A, B, D, E, and F are incorrect based on the above. (Objective 3.3)
3. Given:
class TKO {
public static void main(String[] args) {
String s = "-";
Integer x = 343;
long L343 = 343L;
if(x.equals(L343)) s += ".e1 ";
if(x.equals(343)) s += ".e2 ";
Short s1 = (short)((new Short((short)343)) / (new Short((short)49)));
if(s1 == 7) s += "=s ";
if(s1 < new Integer(7+1)) s += "fly ";
System.out.println(s);
} }
Which of the following will be included in the output String s? (Choose all that apply.)
A. .e1
B. .e2
C. =s
D. fly
E. None of the above
F. Compilation fails
G. An exception is thrown at runtime
Answer:
B, C, and D are correct. Remember, that the equals() method for the integer wrappers
will only return true if the two primitive types and the two values are equal. With C, it's
okay to unbox and use ==. For D, it's okay to create a wrapper object with an expression,
and unbox it for comparison with a primitive.
A, E, F, and G are incorrect based on the above. (Remember that A is using the equals() method to try to compare two different types.) (Objective 3.1)
A, E, F, and G are incorrect based on the above. (Remember that A is using the equals() method to try to compare two different types.) (Objective 3.1)
4. Given:
import java.io.*;
class Keyboard { }
public class Computer implements Serializable {
private Keyboard k = new Keyboard();
public static void main(String[] args) {
Computer c = new Computer();
c.storeIt(c);
}
void storeIt(Computer c) {
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myFile"));
os.writeObject(c);
os.close();
System.out.println("done");
} catch (Exception x) {System.out.println("exc"); }
}
}
What is the result? (Choose all that apply.)
A. exc
B. done
C. Compilation fails
D. Exactly one object is serialized
E. Exactly two objects are serialized
Answer:
A is correct. An instance of type Computer Has-a Keyboard. Because Keyboard doesn't
implement Serializable, any attempt to serialize an instance of Computer will cause an
exception to be thrown.
B, C, D, and E are incorrect based on the above. If Keyboard did implement Serializable then two objects would have been serialized. (Objective 3.3)
B, C, D, and E are incorrect based on the above. If Keyboard did implement Serializable then two objects would have been serialized. (Objective 3.3)
5. Using the fewest fragments possible (and filling the fewest slots possible), complete the code below so that the class builds a directory named "dir3" and creates a file named "file3" inside "dir3". Note you can use each fragment either zero or one times. Code:
import java.io.______________
class Maker {
public static void main(String[] args) {
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
___________ ___________ ___________
} }
Fragments:
| File; | FileDescriptor; | FileWriter; | Directory; |
| try { | .createNewDir(); | File dir | File |
| { } | (Exception x) | ("dir3"); | file |
| file | .createNewFile(); | = new File | = new File |
| dir | (dir, "file3"); | (dir, file); | .createFile(); |
| } catch | ("dir3", "file3"); | .mkdir(); | File file |
Answer:
import java.io.File;
class Maker {
public static void main(String[] args) {
try {
File dir = new File("dir3");
dir.mkdir();
File file = new File(dir, "file3");
file.createNewFile();
} catch (Exception x) { }
} }
Notes: The new File statements don't make actual files or directories, just objects. You need the mkdir() and createNewFile() methods to actually create the directory and the file. (Objective 3.2)
6. Given that 1119280000000L is roughly the number of milliseconds from Jan. 1, 1970, to June 20, 2005, and that you want to print that date in German, using the LONG style such that "June" will be displayed as "Juni", complete the code using the fragments below. Note: you can use each fragment either zero or one times, and you might not need to fill all of the slots. Code:
import java.___________
import java.___________
class DateTwo {
public static void main(String[] args) {
Date d = new Date(1119280000000L);
DateFormat df = ___________________________
________________ , _________________ );
System.out.println(________________
}
}
Fragments:| io.*; | new DateFormat( | Locale.LONG |
| nio.*; | DateFormat.getInstance( | Locale.GERMANY |
| util.*; | DateFormat.getDateInstance( | DateFormat.LONG |
| text.*; | util.regex; | DateFormat.GERMANY |
| date.*; | df.format(d)); | d.format(df)); |
Answer:
import java.util.*;
import java.text.*;
class DateTwo {
public static void main(String[] args) {
Date d = new Date(1119280000000L);
DateFormat df = DateFormat.getDateInstance(
DateFormat.LONG, Locale.GERMANY);
System.out.println(df.format(d));
}
}
Notes: Remember that you must build DateFormat objects using static methods. Also
remember that you must specify a Locale for a DateFormat object at the time of instantiation.
The getInstance() method does not take a Locale. (Objective 3.4)
7. Given:
import java.io.*;
class Directories {
static String [] dirs = {"dir1", "dir2"};
public static void main(String [] args) {
for (String d : dirs) {
// insert code 1 here
File file = new File(path, args[0]);
// insert code 2 here
}
}
}
and that the invocationjava Directories file2.txt
is issued from a directory that has two subdirectories, "dir1" and "dir2", and that "dir1" has a file "file1.txt" and "dir2" has a file "file2.txt", and the output is "false true", which set(s) of code fragments must be inserted? (Choose all that apply.)
A. String path = d; System.out.print(file.exists() + " ");
B. String path = d; System.out.print(file.isFile() + " ");
C. String path = File.separator + d; System.out.print(file.exists() + " ");
D. String path = File.separator + d; System.out.print(file.isFile() + " ");
Answer:
A and B are correct. Because you are invoking the program from the directory whose
direct subdirectories are to be searched, you don't start your path with a File.separator
character. The exists() method tests for either files or directories; the isFile()
method tests only for files. Since we're looking for a file, both methods work.
C and D are incorrect based on the above. (Objective 3.2)
C and D are incorrect based on the above. (Objective 3.2)
8. Given:
import java.io.*;
public class TestSer {
public static void main(String[] args) {
SpecialSerial s = new SpecialSerial();
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myFile"));
os.writeObject(s); os.close();
System.out.print(++s.z + " ");
ObjectInputStream is = new ObjectInputStream(
new FileInputStream("myFile"));
SpecialSerial s2 = (SpecialSerial)is.readObject();
is.close();
System.out.println(s2.y + " " + s2.z);
} catch (Exception x) {System.out.println("exc"); }
}
}
class SpecialSerial implements Serializable {
transient int y = 7;
static int z = 9;
}
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output is 10 0 9
C. The output is 10 0 10
D. The output is 10 7 9
E. The output is 10 7 10
F. In order to alter the standard deserialization process you would implement the readObject() method in SpecialSerial
G. In order to alter the standard deserialization process you would implement the defaultReadObject() method in SpecialSerial
Answer:
C and F are correct. C is correct because static and transient variables are not
serialized when an object is serialized. F is a valid statement.
A, B, D, and E are incorrect based on the above. G is incorrect because you don't implement the defaultReadObject() method, you call it from within the readObject()method, along with any custom read operations your class needs. (Objective 3.3)
A, B, D, and E are incorrect based on the above. G is incorrect because you don't implement the defaultReadObject() method, you call it from within the readObject()method, along with any custom read operations your class needs. (Objective 3.3)
9. Given:
3. public class Theory {
4. public static void main(String[] args) {
5. String s1 = "abc";
6. String s2 = s1;
7. s1 += "d";
8. System.out.println(s1 + " " + s2 + " " + (s1==s2));
9.
10. StringBuffer sb1 = new StringBuffer("abc");
11. StringBuffer sb2 = sb1;
12. sb1.append("d");
13. System.out.println(sb1 + " " + sb2 + " " + (sb1==sb2));
14. }
15. }
Which are true? (Choose all that apply.)
A. Compilation fails
B. The first line of output is abc abc true
C. The first line of output is abc abc false
D. The first line of output is abcd abc false
E. The second line of output is abcd abc false
F. The second line of output is abcd abcd true
G. The second line of output is abcd abcd false
Answer:
D and F are correct. While String objects are immutable, references to Strings are mutable.
The code s1 += "d"; creates a new String object. StringBuffer objects are mutable, so the
append() is changing the single StringBuffer object to which both StringBuffer references
refer.
A, B, C, E, and G are incorrect based on the above. (Objective 3.1)
A, B, C, E, and G are incorrect based on the above. (Objective 3.1)
10. Given:
3. import java.io.*;
4. public class ReadingFor {
5. public static void main(String[] args) {
6. String s;
7. try {
8. FileReader fr = new FileReader("myfile.txt");
9. BufferedReader br = new BufferedReader(fr);
10. while((s = br.readLine()) != null)
11. System.out.println(s);
12. br.flush();
13. } catch (IOException e) { System.out.println("io error"); }
16. }
17. }
And given that myfile.txt contains the following two lines of data:
ab cd
What is the result?
A. ab
B. abcd
C. ab cd
D. a b c d
E. Compilation fails
Answer:
E is correct. You need to call flush() only when you're writing data. Readers don't have
flush() methods. If not for the call to flush(), answer C would be correct.
A, B, C, and D are incorrect based on the above. (Objective 3.2)
A, B, C, and D are incorrect based on the above. (Objective 3.2)
11. Given:
3. import java.io.*;
4. public class Talker {
5. public static void main(String[] args) {
6. Console c = System.console();
7. String u = c.readLine("%s", "username: ");
8. System.out.println("hello " + u);
9. String pw;
10. if(c != null && (pw = c.readPassword("%s", "password: ")) != null)
11. // check for valid password
12. }
13. }
If line 6 creates a valid Console object, and if the user enters fred as a username and 1234 as a
password, what is the result? (Choose all that apply.)
A.
username:
password:
B.
username: fred
password:
C.
username: fred
password: 1234
D. Compilation fails
E. An exception is thrown at runtime
Answer:
D is correct. The readPassword() method returns a char[]. If a char[] were used,
answer B would be correct.
A, B, C, and E are incorrect based on the above. (Objective 3.2)
A, B, C, and E are incorrect based on the above. (Objective 3.2)
12. Given:
3. import java.io.*;
4. class Vehicle { }
5. class Wheels { }
6. class Car extends Vehicle implements Serializable { }
7. class Ford extends Car { }
8. class Dodge extends Car {
9. Wheels w = new Wheels();
10. }
Instances of which class(es) can be serialized? (Choose all that apply.)
A. Car
B. Ford
C. Dodge
D. Wheels
E. Vehicle
Answer:
A and B are correct. Dodge instances cannot be serialized because they "have" an instance
of Wheels, which is not serializable. Vehicle instances cannot be serialized even though the
subclass Car can be.
C, D, and E are incorrect based on the above. (Objective 3.3)
C, D, and E are incorrect based on the above. (Objective 3.3)
13. Given:
3. import java.text.*;
4. public class Slice {
5. public static void main(String[] args) {
6. String s = "987.123456";
7. double d = 987.123456d;
8. NumberFormat nf = NumberFormat.getInstance();
9. nf.setMaximumFractionDigits(5);
10. System.out.println(nf.format(d) + " ");
11. try {
12. System.out.println(nf.parse(s));
13. } catch (Exception e) { System.out.println("got exc"); }
14. }
15. }
Which are true? (Choose all that apply.)
A. The output is 987.12345 987.12345
B. The output is 987.12346 987.12345
C. The output is 987.12345 987.123456
D. The output is 987.12346 987.123456
E. The try/catch block is unnecessary
F. The code compiles and runs without exception
G. The invocation of parse() must be placed within a try/catch block
Answer:
D, F, and G are correct. The setMaximumFractionDigits() applies to the formatting
but not the parsing. The try/catch block is placed appropriately. This one might scare you
into thinking that you'll need to memorize more than you really do. If you can remember
that you're formatting the number and parsing the string you should be fine for the exam.
A, B, C, and E are incorrect based on the above. (Objective 3.4)
A, B, C, and E are incorrect based on the above. (Objective 3.4)
14. Given:
3. import java.util.regex.*;
4. public class Archie {
5. public static void main(String[] args) {
6. Pattern p = Pattern.compile(args[0]);
7. Matcher m = p.matcher(args[1]);
8. int count = 0;
9. while(m.find())
10. count++;
11. System.out.print(count);
12. }
13. }
And given the command line invocation:
java Archie "\d+" ab2c4d67
What is the result?
A. 0
B. 3
C. 4
D. 8
E. 9
F. Compilation fails
Answer:
B is correct. The "\d" metacharacter looks for digits, and the + quantifier says look for
"one or more" occurrences. The find() method will find three sets of one or more consecutive
digits: 2, 4, and 67.
A, C, D, E, and F are incorrect based on the above. (Objective 3.5)
A, C, D, E, and F are incorrect based on the above. (Objective 3.5)
15. Given:
import java.util.*;
public class Looking {
public static void main(String[] args) {
String input = "1 2 a 3 45 6";
Scanner sc = new Scanner(input);
int x = 0;
do {
x = sc.nextInt();
System.out.print(x + " ");
} while (x!=0);
}
}
What is the result?
A. 1 2
B. 1 2 3 45 6
C. 1 2 3 4 5 6
D. 1 2 a 3 45 6
E. Compilation fails
F. 1 2 followed by an exception
Answer:
F is correct. The nextXxx() methods are typically invoked after a call to a hasNextXxx(),
which determines whether the next token is of the correct type.
A, B, C, D, and E are incorrect based on the above. (Objective 3.5)
A, B, C, D, and E are incorrect based on the above. (Objective 3.5)
.
regards,
Agni..
Executive
Talent Sprint.
Hyderabad.
for Feedback and Support simply drop a mail in
agnbi2020{at}gmail.com
Remember to replace the {at} with @ in the email addresses
Monday, August 13, 2012
String Handling
Using String, StringBuffer, and StringBuilder (Objective 3.1)
- String objects are immutable, and String reference variables are not.
- If you create a new String without assigning it, it will be lost to your program.
- If you redirect a String reference to a new String, the old String can be lost.
- String methods use zero-based indexes, except for the second argument of substring().
- The String class is final-its methods can't be overridden.
- When the JVM finds a String literal, it is added to the String literal pool.
- Strings have a method: length(); arrays have an attribute named length.
- The StringBuffer's API is the same as the new StringBuilder's API, except that StringBuilder's methods are not synchronized for thread safety.
- StringBuilder methods should run faster than StringBuffer methods.
- All of the following bullets apply to both StringBuffer and StringBuilder:
- They are mutable - they can change without creating a new object.
- StringBuffer methods act on the invoking object, and objects can change without an explicit assignment in the statement.
- StringBuffer equals() is not overridden; it doesn't compare values.
- Remember that chained methods are evaluated from left to right.
- String methods to remember: charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), and trim().
- StringBuffer methods to remember: append(), delete(), insert(), reverse(), and toString().
File I/O (Objective 3.2)
- The classes you need to understand in java.io are File, FileReader, BufferedReader, FileWriter, BufferedWriter, PrintWriter, and Console.
- A new File object doesn't mean there's a new file on your hard drive.
- File objects can represent either a file or a directory.
- The File class lets you manage (add, rename, and delete) files and directories.
- The methods createNewFile() and mkdir() add entries to your file system.
- FileWriter and FileReader are low-level I/O classesYou can use them to write and read files, but they should usually be wrapped.
- Classes in java.io are designed to be "chained" or "wrapped." (This is a common use of the decorator design pattern.)
- It's very common to "wrap" a BufferedReader around a FileReader or a BufferedWriter around a FileWriter, to get access to higher-level (more convenient) methods.
- PrintWriters can be used to wrap other Writers, but as of Java 5 they can be built directly from Files or Strings.
- Java 5 PrintWriters have new append(), format(), and printf() methods.
- Console objects can read non-echoed input and are instantiated using System.console().
Serialization (Objective 3.3)
- The classes you need to understand are all in thejava.io package; they include: ObjectOutputStream and ObjectInputStream primarily, and FileOutputStream and FileInputStream because you will use them to create the low-level streams that the ObjectXxxStream classes will use.
- A class must implement Serializable before its objects can be serialized.
- The ObjectOutputStream.
writeObject() method serializes objects, and the ObjectInputStream.readObject() method deserializes objects. - If you mark an instance variable transient, it will not be serialized even thought the rest of the object's state will be.
- You can supplement a class's automatic serialization process by implementing the writeObject() and readObject() methodsIf you do this, embedding calls to defaultWriteObject() and defaultReadObject(),
respectively, will handle the part of serialization that happens normally. - If a superclass implements Serializable, then its subclasses do automatically.
- If a superclass doesn't implement Serializable, then when a subclass object is deserialized, the superclass constructor will be invoked, along with its superconstructor(s).
- DataInputStream and DataOutputStream aren't actually on the exam, inspite of what the Sun objectives say.
Dates, Numbers, and Currency (Objective 3.4)
- The classes you need to understand are java.util.Date, java.util.Calendar, java.text.DateFormat, java.text.NumberFormat, and java.util.Locale.
- Most of the Date class's methods have been deprecated.
- A Date is stored as a long, the number of milliseconds since January 1, 1970.
- Date objects are go-betweens the Calendar and Locale classes.
- The Calendar provides a powerful set of methods to manipulate dates, performing tasks such as getting days of the week, or adding some number of months or years (or other increments) to a date.
- Create Calendar instances using static factory methods (getInstance()).
- The Calendar methods you should understand are add(), which allows you to add or subtract various pieces (minutes, days, years, and so on) of dates, and roll(), which works like add() but doesn't increment a date's bigger pieces(For example: adding 10 months to an October date changes the month to August, but doesn't increment the Calendar's year value.)
- DateFormat instances are created using static factory methods (getInstance() and getDateInstance()).
- There are several format "styles" available in the DateFormat class.
- DateFormat styles can be applied against various Locales to create a wide array of outputs for any given date.
- The DateFormat.format() method is used to create Strings containing properly formatted dates.
- The Locale class is used in conjunction with DateFormat and NumberFormat.
- Both DateFormat and NumberFormat objects can be constructed with a specific, immutable Locale.
- For the exam you should understand creating Locales using language, or a combination of language and country.
Parsing, Tokenizing, and Formatting (Objective 3.5)
- regex is short for regular expressions, which are the patterns used to search for data within large data sources.
- regex is a sub-language that exists in Java and other languages (such as Perl).
- regex lets you to create search patterns using literal characters or metacharactersMetacharacters allow you to search for slightly more abstract data like "digits" or "whitespace".
- Study the \d, \s, \w, and metacharacters
- regex provides for quantifiers which allow you to specify concepts like: "look for one or more digits in a row."
- Study the ?, *, and + greedy quantifiers.
- Remember that metacharacters and Strings don't mix well unless you remember to "escape" them properlyFor instance String s = "\\d";
- The Pattern and Matcher classes have Java's most powerful regex capabilities.
- You should understand the Pattern compile() method and the Matcher matches(), pattern(), find(), start(), and group() methods.
- You WON'T need to understand Matcher's replacement-oriented methods.
- You can use java.util.Scanner to do simple regex searches, but it is primarily intended for tokenizing.
- Tokenizing is the process of splitting delimited data into small pieces.
- In tokenizing, the data you want is called tokens, and the strings that separate the tokens are called delimiters.
- Tokenizing can be done with the Scanner class, or with String.split().
- Delimiters are single characters like commas, or complex regex expressions.
- The Scanner class allows you to tokenize data from within a loop, which allows you to stop whenever you want to.
- The Scanner class allows you to tokenize Strings or streams or files.
- The String.split() method tokenizes the entire source data all at once, so large amounts of data can be quite slow to process.
- New to Java 5 are two methods used to format data for output. These methods are format() and printf()These methods are found in the PrintStream class, an instance of which is the out in System.out.
- The format() and printf() methods have identical functionality.
- Formatting data with printf() (or format()) is accomplished using formatting strings that are associated with primitive or string arguments.
- The format() method allows you to mix literals in with your format strings.
- The format string values you should know are
- Flags: -, +, 0, "," , and (
- Conversions: b, c, d, f, and s
- If your conversion character doesn't match your argument type, an exception will be thrown.
regards,
Agni..
Executive,
Talent Sprint
Hyderabad.
for Feedback and Support simply drop a mail in
agni2020{at}gmail.com
Remember to replace the {at} with @ in the email addresses
Subscribe to:
Posts (Atom)