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
Friday, August 3, 2012
Exercise-4 (Operators)
1. Given:
class Hexy { public static void main(String[] args) { Integer i = 42; String s = (i<40 i="i" life="life">50)?"universe":"everything"; System.out.println(s); } }
What is the result?
A. null
B. life
C. universe
D. everything
E. Compilation fails
F. An exception is thrown at runtime
Answer:
D is correct. This is a ternary nested in a ternary with a little unboxing thrown in. Both of the ternary expressions are false.
A, B, C, E, and F are incorrect based on the above.(Objective 7.6)
2. Given:A, B, C, E, and F are incorrect based on the above.(Objective 7.6)
class Comp2 { public static void main(String[] args) { float f1 = 2.3f; float[][] f2 = {{42.0f}, {1.7f, 2.3f}, {2.6f, 2.7f}}; float[] f3 = {2.7f}; Long x = 42L; // insert code here System.out.println("true"); } }And the following five code fragments:
F1. if(f1 == f2)
F2. if(f1 == f2[2][1])
F3. if(x == f2[0][0])
F4. if(f1 == f2[1,1])
F5. if(f3 == f2[2])
What is true?
A. One of them will compile, only one will be true
B. Two of them will compile, only one will be true
C. Two of them will compile, two will be true
D. Three of them will compile, only one will be true
E. Three of them will compile, exactly two will be true
F. Three of them will compile, exactly three will be true
Answer:
D is correct. Fragments F2, F3, and F5 will compile, and only F3 is true.
A, B, C, E, and F are incorrect. F1 is incorrect because you can’t compare a primitive to an array. F4 is incorrect syntax to access an element of a two-dimensional array.(Objective 7.6)
3. Given:A, B, C, E, and F are incorrect. F1 is incorrect because you can’t compare a primitive to an array. F4 is incorrect syntax to access an element of a two-dimensional array.(Objective 7.6)
class Fork { public static void main(String[] args) { if(args.length == 1 | args[1].equals("test")) { System.out.println("test case"); } else { System.out.println("production " + args[0]); } } }And the command-line invocation:
java Fork live2
What is the result?
A. test case
B. production live2
C. test case live2
D. Compilation fails
E. An exception is thrown at runtime
Answer:
E is correct. Because the short circuit (||) is not used, both operands are evaluated. Sinceargs[1] is past the args array bounds, an ArrayIndexOutOfBoundsException is thrown.
A, B, C, and D are incorrect based on the above. (Objective 7.6)
4. Given:A, B, C, and D are incorrect based on the above. (Objective 7.6)
class Feline { public static void main(String[] args) { Long x = 42L; Long y = 44L; System.out.print(" " + 7 + 2 + " "); System.out.print(foo() + x + 5 + " "); System.out.println(x + y + foo()); } static String foo() { return "foo"; } }What is the result?
A. 9 foo47 86foo
B. 9 foo47 4244foo
C. 9 foo425 86foo
D. 9 foo425 4244foo
E. 72 foo47 86foo
F. 72 foo47 4244foo
G. 72 foo425 86foo
H. 72 foo425 4244foo
I. Compilation fails
Answer:
G is correct. Concatenation runs from left to right, and if either operand is a String,the operands are concatenated. If both operands are numbers they are added together.Unboxing works in conjunction with concatenation.
A, B, C, D, E, F, H, and I are incorrect based on the above. (Objective 7.6)
5. Place the fragments into the code to produce the output 33. Note, you must use each fragment exactly once.A, B, C, D, E, F, H, and I are incorrect based on the above. (Objective 7.6)
CODE:
class Incr { public static void main(String[] args) { Integer x = 7; int y = 2; x ___ ___; ___ ___ ___; ___ ___ ___; ___ ___ ___; System.out.println(x); } }FRAGMENTS:
y | y | y | y |
y | x | x | |
-= | *= | *= | *= |
Answer:
class Incr { public static void main(String[] args) { Integer x = 7; int y = 2; x *= x; y *= y; y *= y; x -= y; System.out.println(x); } }Yeah, we know it’s kind of puzzle-y, but you might encounter something like it on the real exam. (Objective 7.6)
public class Twisty { { index = 1; } int index; public static void main(String[] args) { new Twisty().go(); } void go() { int [][] dd = {{9,8,7}, {6,5,4}, {3,2,1,0}}; System.out.println(dd[index++][index++]); } }What is the result? (Choose all that apply.)
A. 1
B. 2
C. 4
D. 6
E. 8
F. Compilation fails
G. An exception is thrown at runtime
Answer:
C is correct. Multidimensional arrays' dimensions can be inconsistent, the code uses an initialization block, and the increment operators are both post-increment operators.
A, B, D, E, F, and G are incorrect based on the above. (Objective 1.3)
7. Given:A, B, D, E, F, and G are incorrect based on the above. (Objective 1.3)
import java.lang.*; import java.io.*; public class McGee { public static void main(String[] args) { Days d1 = Days.TH; Days d2 = Days.M; for(Days d: Days.values()) { if(d.equals(Days.F)) break; d2 = d; } System.out.println((d1 == d2)?"same old" : "newly new"); } enum Days {M, T, W, TH, F, SA, SU}; }What is the result?
A. same old
B. newly new
C. Compilation fails due to multiple errors
D. Compilation fails due only to an error on line 7
E. Compilation fails due only to an error on line 8
F. Compilation fails due only to an error on line 11
G. Compilation fails due only to an error on line 13
Answer:
A is correct. All of this syntax is correct. The for-each iterates through the enum using the values() method to return an array. Enums can be compared using either equals() or ==. Enums can be used in a ternary operator's Boolean test.
B, C, D, E, F, and G are incorrect based on the above. (Objective 7.6)
8. Given:B, C, D, E, F, and G are incorrect based on the above. (Objective 7.6)
public class SpecialOps { public static void main(String[] args) { String s = ""; Boolean b1 = true; Boolean b2 = false; if((b2 = false) | (21%5) > 2) s += "x"; if(b1 || (b2 = true)) s += "y"; if(b2 == true) s += "z"; System.out.println(s); } }Which are true? (Choose all that apply.)
A. Compilation fails
B. x will be included in the output
C. y will be included in the output
D. z will be included in the output
E. An exception is thrown at runtime
Answer:
C is correct. First of all, boxing takes care of the Boolean. Line 9 uses the modulus operator, which returns the remainder of the division, which in this case is 1. Also, line 9 sets b2 to false, and it doesn't test b2's value. Line 10 sets b2 to true, and it doesn’t test its value; however, the short circuit operator keeps the expression b2 = true from being executed.
A, B, D, and E are incorrect based on the above. (Objective 7.6)
9. Given:A, B, D, and E are incorrect based on the above. (Objective 7.6)
public class Spock { public static void main(String[] args) { int mask = 0; int count = 0; if( ((5 < 7) || (++count < 10)) | mask++ < 10 ) mask = mask + 1; if( (6 > 8) ^ false) mask = mask + 10; if( !(mask > 1) && ++count > 1) mask = mask + 100; System.out.println(mask + " " + count); } }Which two answers are true about the value of mask and the value of count at line 10?(Choose two.)
A. mask is 0
B. mask is 1
C. mask is 2
D. mask is 10
E. mask is greater than 10
F. count is 0
G. count is greater than 0
Answer:
C and F are correct. At line 7 the || keeps count from being incremented, but the | allows mask to be incremented. At line 8 the ^ returns true only if exactly one operand is true. At line 9 mask is 2 and the && keeps count from being incremented.
A, B, D, E, and G are incorrect based on the above. (Objective 7.6)
10. Given:A, B, D, E, and G are incorrect based on the above. (Objective 7.6)
interface Vessel { } interface Toy { } class Boat implements Vessel { } class Speedboat extends Boat implements Toy { } public class Tree { public static void main(String[] args) { String s = "0"; Boat b = new Boat(); Boat b2 = new Speedboat(); Speedboat s2 = new Speedboat(); if((b instanceof Vessel) && (b2 instanceof Toy)) s += "1"; if((s2 instanceof Vessel) && (s2 instanceof Toy)) s += "2"; System.out.println(s); } }What is the result?
A. 0
B. 01
C. 02
D. 012
E. Compilation fails
F. An exception is thrown at runtime
Answer:
D is correct. First, remember that instanceof can look up through multiple levels of an inheritance tree. Also remember that instanceof is commonly used before attempting a downcast, so in this case, after line 15, it would be possible to say Speedboat s3 = (Speedboat)b2;.
A, B, C, E, and F are incorrect based on the above. (Objective 7.6)
A, B, C, E, and F are incorrect based on the above. (Objective 7.6)
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
Wednesday, August 1, 2012
Operators
Relational Operators (Objective 7.6)
- Relational operators always result in a boolean value (true or false).
- There are six relational operators: >, >=, <, <=, ==, and !=.
- The last two (== and !=) are sometimes referred to as equality operators.
- When comparing characters, Java uses the Unicode value of the character as the numerical value.
- There are two equality operators: == and != .
- Four types of things can be tested: numbers, characters, booleans, and reference variables.
- When comparing reference variables, == returns true only if both references refer to the same object.
- instanceof is for reference variables only, and checks for whether the object is of a particular type.
- The instanceof operator can be used only to test objects (or null) against class types that are in the same class hierarchy.
- For interfaces, an object passes the instanceof test if any of its superclasses implement the interface on the right side of the instanceof operator.
- There are four primary math operators: add, subtract, multiply, and divide.
- The remainder operator (%), returns the remainder of a division.
- Expressions are evaluated from left to right, unless you add parentheses, or unless some operators in the expression have higher precedence than others.
- The *, /, and % operators have higher precedence than + and -.
- If either operand is a String, the + operator concatenates the operands.
- If both operands are numeric, the + operator adds the operands.
- Prefix operators (++ and --) run before the value is used in the expression.
- Postfix operators (++ and --) run after the value is used in the expression.
- In any expression, both operands are fully evaluated before the operator is applied.
- Variables marked final cannot be incremented or decremented.
- Returns one of two values based on whether a boolean expression is true or false.
- Returns the value after the ? if the expression is true.
- Returns the value after the : if the expression is false.
- The exam covers six "logical" operators: &, |, ^, !, &&, and ||.
- Logical operators work with two expressions (except for !) that must resolve to boolean values.
- The && and & operators return true only if both operands are true.
- The || and | operators return true if either or both operands are true.
- The && and || operators are known as short-circuit operators.
- The && operator does not evaluate the right operand if the left operand is false.
- The || does not evaluate the right operand if the left operand is true.
- The & and | operators always evaluate both operands.
- The ^ operator (called the "logical XOR"), returns true if exactly one operand is true.
- The ! operator (called the "inversion" operator), returns the opposite value of the boolean operand it precedes.
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
Sunday, July 29, 2012
OCPJ Exercise-3 (Basics)
1. Given:
class CardBoard { Short story = 200; CardBoard go(CardBoard cb) { cb = null; return cb; } public static void main(String[] args) { CardBoard c1 = new CardBoard(); CardBoard c2 = new CardBoard(); CardBoard c3 = c1.go(c2); c1 = null; // do Stuff } }
When // doStuff is reached, how many objects are eligible for GC?
A. 0
B. 1
C. 2
D. Compilation fails
E. It is not possible to know
F. An exception is thrown at runtime
Answer:
C is correct. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
A, B, D, E, and F are incorrect based on the above. (Objective 7.4)
2. Given:A, B, D, E, and F are incorrect based on the above. (Objective 7.4)
class Alien { String invade(short ships) { return "a few"; } String invade(short... ships) { return "many"; } } class Defender { public static void main(String [] args) { System.out.println(new Alien().invade(7)); } }What is the result?
A. many
B. a few
C. Compilation fails
D. The output is not predictable
E. An exception is thrown at runtime
Answer:
C is correct, compilation fails. The var-args declaration is fine, but invade takes a short,so the argument 7 needs to be cast to a short. With the cast, the answer is B, 'a few'.
A, B, D, and E are incorrect based on the above. (Objective 1.3)
3. Given:
A, B, D, and E are incorrect based on the above. (Objective 1.3)
class Dims { public static void main(String[] args) { int[][] a = {{1,2,}, {3,4}}; int[] b = (int[]) a[1]; Object o1 = a; int[][] a2 = (int[][]) o1; int[] b2 = (int[]) o1; System.out.println(b[1]); } }What is the result?
A. 2
B. 4
C. An exception is thrown at runtime
D. Compilation fails due to an error on line 4
E. Compilation fails due to an error on line 5
F. Compilation fails due to an error on line 6
G. Compilation fails due to an error on line 7
Answer:
C is correct. A ClassCastException is thrown at line 7 because o1 refers to an int[][] not an int[]. If line 7 was removed, the output would be 4.
A, B, D, E, F, and G are incorrect based on the above. (Objective 1.3)
4. Given:
A, B, D, E, F, and G are incorrect based on the above. (Objective 1.3)
class Mixer { Mixer() { } Mixer(Mixer m) { m1 = m; } Mixer m1; public static void main(String[] args) { Mixer m2 = new Mixer(); Mixer m3 = new Mixer(m2); m3.go(); Mixer m4 = m3.m1; m4.go(); Mixer m5 = m2.m1; m5.go(); } void go() { System.out.print("hi "); } }What is the result?
A. hi
B. hi hi
C. hi hi hi
D. Compilation fails
E. hi, followed by an exception
F. hi hi, followed by an exception
Answer:
F is correct. The m2 object's m1 instance variable is never initialized, so when m5 tries to use it a NullPointerException is thrown.
A, B, C, D, and E are incorrect based on the above. (Objective 7.3)
5. Given:
A, B, C, D, and E are incorrect based on the above. (Objective 7.3)
class Fizz { int x = 5; public static void main(String[] args) { final Fizz f1 = new Fizz(); Fizz f2 = new Fizz(); Fizz f3 = FizzSwitch(f1,f2); System.out.println((f1 == f3) + " " + (f1.x == f3.x)); } static Fizz FizzSwitch(Fizz x, Fizz y) { final Fizz z = x; z.x = 6; return z; } }What is the result?
A. true true
B. false true
C. true false
D. false false
E. Compilation fails
F. An exception is thrown at runtime
Answer:
A is correct. The references f1, z, and f3 all refer to the same instance of Fizz. The final modifier assures that a reference variable cannot be referred to a different object, but final doesn't keep the object's state from changing.
B, C, D, E, and F are incorrect based on the above. (Objective 7.3)
6. Given:
B, C, D, E, and F are incorrect based on the above. (Objective 7.3)
class Bird { { System.out.print("b1 "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk extends Raptor { public static void main(String[] args) { System.out.print("pre "); new Hawk(); System.out.println("hawk "); } }What is the result?
A. pre b1 b2 r3 r2 hawk
B. pre b2 b1 r2 r3 hawk
C. pre b2 b1 r2 r3 hawk r1 r4
D. r1 r4 pre b1 b2 r3 r2 hawk
E. r1 r4 pre b2 b1 r2 r3 hawk
F. pre r1 r4 b1 b2 r3 r2 hawk
G. pre r1 r4 b2 b1 r2 r3 hawk
H. The order of output cannot be predicted
I. Compilation fails
Answer:
D is correct. Static init blocks are executed at class loading time, instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down.
A, B, C, E, F, G, H, and I are incorrect based on the above. Note: you'll probably never see this many choices on the real exam! (Objective 1.3)
7. Given:
A, B, C, E, F, G, H, and I are incorrect based on the above. Note: you'll probably never see this many choices on the real exam! (Objective 1.3)
public class Bridge { public enum Suits { CLUBS(20), DIAMONDS(20), HEARTS(30), SPADES(30), NOTRUMP(40) { public int getValue(int bid) { return ((bid-1)*30)+40; } }; Suits(int points) { this.points = points; } private int points; public int getValue(int bid) { return points * bid; } } public static void main(String[] args) { System.out.println(Suits.NOTRUMP.getBidValue(3)); System.out.println(Suits.SPADES + " " + Suits.SPADES.points); System.out.println(Suits.values()); } }Which are true? (Choose all that apply.)
A. The output could contain 30
B. The output could contain @bf73fa
C. The output could contain DIAMONDS
D. Compilation fails due to an error on line 4
E. Compilation fails due to an error on line 5
F. Compilation fails due to an error on line 6
G. Compilation fails due to an error on line 7
H. Compilation fails due to an error within lines 10 to 12
Answer:
A and B are correct. The code compiles and runs without exception. The values() method returns an array reference, not the contents of the enum, so DIAMONDS is never printed.
C, D, E, F, G, and H are incorrect based on the above. (Objective 1.3)
8. Given:C, D, E, F, G, and H are incorrect based on the above. (Objective 1.3)
public class Ouch { static int ouch = 7; public static void main(String[] args) { new Ouch().go(ouch); System.out.print(" " + ouch); } void go(int ouch) { ouch++; for(int ouch = 3; ouch < 6; ouch++) ; System.out.print(" " + ouch); } }What is the result?
A. 5 7
B. 5 8
C. 8 7
D. 8 8
E. Compilation fails
F. An exception is thrown at runtime
Answer:
E is correct. The parameter declared on line 7 is valid (although ugly), but the variable name ouch cannot be declared again on line 9 in the same scope as the declaration on line 7.
A, B, C, D, and F are incorrect based on the above. (Objective 1.3)
9. Given:
A, B, C, D, and F are incorrect based on the above. (Objective 1.3)
public class Bertha { static String s = ""; public static void main(String[] args) { int x = 4; Boolean y = true; short[] sa = {1,2,3}; doStuff(x, y); doStuff(x); doStuff(sa, sa); System.out.println(s); } static void doStuff(Object o) { s += "1"; } static void doStuff(Object... o) { s += "2"; } static void doStuff(Integer... i) { s += "3"; } static void doStuff(Long L) { s += "4"; } }What is the result?
A. 212
B. 232
C. 234
D. 312
E. 332
F. 334
G. Compilation fails
Answer:
A is correct. It's legal to autobox and then widen. The first call to doStuff() boxes the int to an Integer then passes two objects. The second call cannot widen and then box (making the Long method unusable), so it boxes the int to an Integer. As always, a var-args method will be chosen only if no non-var-arg method is possible. The third call is passing two objects—they are of type 'short array.'
B, C, D, E, F, and G are incorrect based on the above. (Objective 3.1)
10. Given:
B, C, D, E, F, and G are incorrect based on the above. (Objective 3.1)
class Dozens { int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12}; } public class Eggs { public static void main(String[] args) { Dozens [] da = new Dozens[3]; da[0] = new Dozens(); Dozens d = new Dozens(); da[1] = d; d = null; da[1] = null; // do stuff } }Which two are true about the objects created within main(), and eligible for garbage collection when line 12 is reached?
A. Three objects were created
B. Four objects were created
C. Five objects were created
D. Zero objects are eligible for GC
E. One object is eligible for GC
F. Two objects are eligible for GC
G. Three objects are eligible for GC
Answer:
C and F are correct. da refers to an object of type "Dozens array," and each Dozens object that is created comes with its own "int array" object. When line 14 is reached, only the second Dozens object (and its "int array" object) are not reachable.
A, B, D, E, and G are incorrect based on the above. (Objective 7.4)
11. Given:
A, B, D, E, and G are incorrect based on the above. (Objective 7.4)
class Beta { } class Alpha { static Beta b1; Beta b2; } public class Tester { public static void main(String[] args) { Beta b1 = new Beta(); Beta b2 = new Beta(); Alpha a1 = new Alpha(); Alpha a2 = new Alpha(); a1.b1 = b1; a1.b2 = b1; a2.b2 = b2; a1 = null; b1 = null; b2 = null; // do stuff } }When line 16 is reached, how many objects will be eligible for garbage collection?
A. 0
B. 1
C. 2
D. 3
E. 4
F. 5
Answer:
B is correct. It should be clear that there is still a reference to the object referred to by a2, and that there is still a reference to the object referred to by a2.b2. What might be less clear is that you can still access the other Beta object through the static variable a2.b1—because it's static.
A, C, D, E, and F are incorrect based on the above. (Objective 7.4)
12. Given:
A, C, D, E, and F are incorrect based on the above. (Objective 7.4)
class Box { int size; Box(int s) { size = s; } } public class Laser { public static void main(String[] args) { Box b1 = new Box(5); Box[] ba = go(b1, new Box(6)); ba[0] = b1; for(Box b : ba) System.out.print(b.size + " "); } static Box[] go(Box b1, Box b2) { b1.size = 4; Box[] ma = {b2, b1}; return ma; } }What is the result?
A. 4 4
B. 5 4
C. 6 4
D. 4 5
E. 5 5
F. Compilation fails
Answer:
A is correct. Although main()'s b1 is a different reference variable than go()'s b1, they refer to the same Box object.
B, C, D, E, and F are incorrect based on the above. (Objective 7.3)
13. Given:
B, C, D, E, and F are incorrect based on the above. (Objective 7.3)
public class Dark { int x = 3; public static void main(String[] args) { new Dark().go1(); } void go1() { int x; go2(++x); } void go2(int y) { int x = ++y; System.out.println(x); } }what is the result?
A. 2
B. 3
C. 4
D. 5
E. Compilation fails
F. An exception is thrown at runtime
Answer:
E is correct. In go1() the local variable x is not initialized.
A, B, C, D, and F are incorrect based on the above. (Objective 1.3)
A, B, C, D, and F are incorrect based on the above. (Objective 1.3)
regards,
Agni..
Executive,
Talent Sprint Edu. Pvt Ltd.
Hyderabad.
for Feedback and Support simply drop a mail in
agni2020{at}gmail.com
Remember to replace the {at} with @ in the email addresses
Thursday, July 26, 2012
Basic Points
Bullet Points on some Basic Concepts:
Stack and Heap
- Local variables (method variables) live on the stack.
- Objects and their instance variables live on the heap.
Literals and Primitive Casting (Objective 1.3)
- Integer literals can be decimal, octal (e.g. 013), or hexadecimal (e.g. 0x3d).
- Literals for longs end in L or l.
- Float literals end in F or f, double literals end in a digit or D or d.
- The boolean literals are true and false.
- Literals for chars are a single character inside single quotes: 'd'.
Scope (Objectives 1.3 and 7.6)
- Scope refers to the lifetime of a variable.
- There are four basic scopes:
- Static variables live basically as long as their class lives.
- Instance variables live as long as their object lives.
- Local variables live as long as their method is on the stack; however, if their method invokes another method, they are temporarily unavailable.
- Block variables (e.g., in a for or an if) live until the block completes.
Basic Assignments (Objectives 1.3 and 7.6)
- Literal integers are implicitly ints.
- Integer expressions always result in an int-sized result, never smaller.
- Floating-point numbers are implicitly doubles (64 bits).
- Narrowing a primitive truncates the high order bits.
- Compound assignments (e.g. +=), perform an automatic cast.
- A reference variable holds the bits that are used to refer to an object.
- Reference variables can refer to subclasses of the declared type but not to superclasses.
- When creating a new object, e.g., Button b = new Button(); three things happen:
- Make a reference variable named b, of type Button
- Create a new Button object
- Assign the Button object to the reference variable b
Using a Variable or Array Element That Is Uninitialized and Unassigned (Objectives 1.3 and 7.6)
- When an array of objects is instantiated, objects within the array are not instantiated automatically, but all the references get the default value of null.
- When an array of primitives is instantiated, elements get default values.
- Instance variables are always initialized with a default value.
- Local/automatic/method variables are never given a default value. If you attempt to use one before initializing it, you'll get a compiler error.
Passing Variables into Methods (Objective 7.3)
- Methods can take primitives and/or object references as arguments.
- Method arguments are always copies.
- Method arguments are never actual objects (they can be references to objects).
- A primitive argument is an unattached copy of the original primitive.
- A reference argument is another copy of a reference to the original object.
- Shadowing occurs when two variables with different scopes share the same name. This leads to hard-to-find bugs, and hard-to-answer exam questions.
Array Declaration, Construction, and Initialization (Obj. 1.3)
- Arrays can hold primitives or objects, but the array itself is always an object.
- When you declare an array, the brackets can be left or right of the name.
- It is never legal to include the size of an array in the declaration.
- You must include the size of an array when you construct it (using new) unless you are creating an anonymous array.
- Elements in an array of objects are not automatically created, although primitive array elements are given default values.
- You'll get a NullPointerException if you try to use an array element in an object array, if that element does not refer to a real object.
- Arrays are indexed beginning with zero.
- An ArrayIndexOutOfBoundsException occurs if you use a bad index value.
- Arrays have a length variable whose value is the number of array elements.
- The last index you can access is always one less than the length of the array.
- Multidimensional arrays are just arrays of arrays.
- The dimensions in a multidimensional array can have different lengths.
- An array of primitives can accept any value that can be promoted implicitly to the array's declared type;. e.g., a byte variable can go in an int array.
- An array of objects can hold any object that passes the IS-A (or instanceof) test for the declared type of the array. For example, if Horse extends Animal, then a Horse object can go into an Animal array.
- If you assign an array to a previously declared array reference, the array you're assigning must be the same dimension as the reference you're assigning it to.
- You can assign an array of one type to a previously declared array reference of one of its supertypes. For example, a Honda array can be assigned to an array declared as type Car (assuming Honda extends Car).
Initialization Blocks (Objectives 1.3 and 7.6)
- Static initialization blocks run once, when the class is first loaded.
- Instance initialization blocks run every time a new instance is created. They run after all super-constructors and before the constructor's code has run.
- If multiple init blocks exist in a class, they follow the rules stated above, AND they run in the order in which they appear in the source file.
Using Wrappers (Objective 3.1)
- The wrapper classes correlate to the primitive types.
- Wrappers have two main functions:
- To wrap primitives so that they can be handled like objects
- To provide utility methods for primitives (usually conversions)
- The three most important method families are
- xxxValue() Takes no arguments, returns a primitive
- parseXxx() Takes a String, returns a primitive, throws NFE
- valueOf() Takes a String, returns a wrapped object, throws NFE
- Wrapper constructors can take a String or a primitive, except for Character, which can only take a char.
- Radix refers to bases (typically) other than 10; octal is radix = 8, hex = 16.
Boxing (Objective 3.1)
- As of Java 5, boxing allows you to convert primitives to wrappers or to convert wrappers to primitives automatically.
- Using == with wrappers created through boxing is tricky; those with the same small values (typically lower than 127), will be ==, larger values will not be ==.
Advanced Overloading (Objectives 1.5 and 5.4)
- Primitive widening uses the "smallest" method argument possible.
- Used individually, boxing and var-args are compatible with overloading.
- You CANNOT widen from one wrapper type to another. (IS-A fails.)
- You CANNOT widen and then box. (An int can't become a Long.)
- You can box and then widen. (An int can become an Object, via an Integer.)
- You can combine var-args with either widening or boxing.
Garbage Collection (Objective 7.4)
- In Java, garbage collection (GC) provides automated memory management.
- The purpose of GC is to delete objects that can't be reached.
- Only the JVM decides when to run the GC, you can only suggest it.
- You can't know the GC algorithm for sure.
- Objects must be considered eligible before they can be garbage collected.
- An object is eligible when no live thread can reach it.
- To reach an object, you must have a live, reachable reference to that object.
- Java applications can run out of memory.
- Islands of objects can be GCed, even though they refer to each other.
- Request garbage collection with System.gc();
- Class Object has a finalize() method.
- The finalize() method is guaranteed to run once and only once before the garbage collector deletes an object.
- The garbage collector makes no guarantees, finalize() may never run.
- You can uneligibilize an object for GC from within finalize().
regards,
M.Agni..
Executive,
Talent Sprint Edu. Pvt Ltd.
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)