Showing posts with label SCJP. Show all posts
Showing posts with label SCJP. Show all posts

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:
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:
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:
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.
CODE:

class Incr {
 public static void main(String[] args) {
  Integer x = 7;
  int y = 2;
  x ___ ___;
  ___ ___ ___;
  ___ ___ ___;
  ___ ___ ___;
  System.out.println(x);
 }
}
FRAGMENTS:
yyyy
yxx
-=*=*=*=
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)
6. Given:
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:
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:
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:

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:
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)

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)
  1. Relational operators always result in a boolean value (true or false).
  2. There are six relational operators: >, >=, <, <=, ==, and !=. 
  3. The last two (== and !=) are sometimes referred to as equality operators.
  4. When comparing characters, Java uses the Unicode value of the character as the numerical value.
Equality operators
  1. There are two equality operators: == and != .
  2. Four types of things can be tested: numbers, characters, booleans, and reference variables.
  3. When comparing reference variables, == returns true only if both references refer to the same object. 
instanceof Operator (Objective 7.6)
  1. instanceof is for reference variables only, and checks for whether the object is of a particular type.
  2. The instanceof operator can be used only to test objects (or null) against class types that are in the same class hierarchy.
  3. For interfaces, an object passes the instanceof test if any of its superclasses implement the interface on the right side of the instanceof operator.
Arithmetic Operators (Objective 7.6)
  1. There are four primary math operators: add, subtract, multiply, and divide.
  2. The remainder operator (%), returns the remainder of a division.
  3. Expressions are evaluated from left to right, unless you add parentheses, or unless some operators in the expression have higher precedence than others.
  4. The *, /, and % operators have higher precedence than + and -.
String Concatenation Operator (Objective 7.6)
  1. If either operand is a String, the + operator concatenates the operands. 
  2. If both operands are numeric, the + operator adds the operands.
Increment/Decrement Operators (Objective 7.6)
  1. Prefix operators (++ and --) run before the value is used in the expression.
  2. Postfix operators (++ and --) run after the value is used in the expression.
  3. In any expression, both operands are fully evaluated before the operator is applied.
  4. Variables marked final cannot be incremented or decremented.
Ternary (Conditional Operator) (Objective 7.6)
  1. Returns one of two values based on whether a boolean expression is true or false.
  2. Returns the value after the ? if the expression is true.
  3. Returns the value after the : if the expression is false.
Logical Operators (Objective 7.6)
  1. The exam covers six "logical" operators: &, |, ^, !, &&, and ||.
  2. Logical operators work with two expressions (except for !) that must resolve to boolean values.
  3. The && and & operators return true only if both operands are true.
  4. The || and | operators return true if either or both operands are true.
  5. The && and || operators are known as short-circuit operators.
  6. The && operator does not evaluate the right operand if the left operand is false.
  7. The || does not evaluate the right operand if the left operand is true.
  8. The & and | operators always evaluate both operands.
  9. The ^ operator (called the "logical XOR"), returns true if exactly one operand is true.
  10. 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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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)


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

Friday, July 20, 2012

OCPJ Exercise - 2




1. Given:
public abstract interface Frobnicate { public void twiddle(String s); }
Which is a correct class? (Choose all that apply.) A.
public abstract class Frob implements Frobnicate {
public abstract void twiddle(String s) { }
}
B.
 public abstract class Frob implements Frobnicate { } 
C.
public class Frob extends Frobnicate {
  public void twiddle(Integer i) { }
}
D.
public class Frob implements Frobnicate {
public void twiddle(Integer i) { }
}
E.
public class Frob implements Frobnicate {
  public void twiddle(String i) { }
  public void twiddle(Integer s) { }
}
Answer:
B is correct, an abstract class need not implement any or all of an interface's methods.
E is correct, the class implements the interface method and additionally overloads the twiddle() method.
A is incorrect because abstract methods have no body. C is incorrect because classes implement interfaces they don't extend them. D is incorrect because overloading a method is not implementing it.
(Objective 5.4)


2. Given:
class Top {
   public Top(String s) { System.out.print("B"); }
}
public class Bottom2 extends Top {
   public Bottom2(String s) { System.out.print("D"); }
   public static void main(String [] args) {
     new Bottom2("C");
     System.out.println(" ");
   } 
}
What is the result?
A. BD
B. DB
C. BDC
D. DBC
E. Compilation fails
Answer:
E is correct. The implied super() call in Bottom2's constructor cannot be satisfied because there isn't a no-arg constructor in Top. A default, no-arg constructor is generated by the compiler only if the class has no constructor defined explicitly.
A, B, C, and D are incorrect based on the above. (Objective 1.6)


3. Given:
class Clidder {
  private final void flipper() { System.out.println("Clidder"); }
}
public class Clidlet extends Clidder {
  public final void flipper() { System.out.println("Clidlet"); }
  public static void main(String [] args) {
  new Clidlet().flipper();
  }
}
What is the result? A. Clidlet
B. Clidder
C. Clidder Clidlet
D. Clidlet Clidder
E. Compilation fails
Answer:
A is correct. Although a final method cannot be overridden, in this case, the method is private, and therefore hidden. The effect is that a new, accessible, method flipper is created. Therefore, no polymorphism occurs in this example, the method invoked is simply that of the child class, and no error occurs.
B, C, D, and E are incorrect based on the preceding.(Objective 5.3)


4. Using the fragments below, complete the following code so it compiles. Note, you may not have to fill all of the slots.
Code:

class AgedP {
   __________ __________ __________ __________ __________
   public AgedP(int x) {
       __________ __________ __________ __________ __________
   }
}

public class Kinder extends AgedP {
   __________ __________ __________ _________ ________ __________
   public Kinder(int x) {
     __________ __________ __________ __________ __________ ();
   }
}
Fragments: Use the following fragments zero or more times:
AgedP super this ( ) { } ;

Answer:
class AgedP {
AgedP() {}
public AgedP(int x) {
}
}
public class Kinder extends AgedP {
public Kinder(int x) {
super();
}
}
As there is no droppable tile for the variable x and the parentheses (in the Kinder constructor), are already in place and empty, there is no way to construct a call to the superclass constructor that takes an argument. Therefore, the only remaining possibility is to create a call to the noargument superclass constructor. This is done as: super();. The line cannot be left blank, as the parentheses are already in place. Further, since the superclass constructor called is the noargument version, this constructor must be created. It will not be created by the compiler because there is another constructor already present.(Objective 5.4)


5 Which statement(s) are true? (Choose all that apply.) A. Cohesion is the OO principle most closely associated with hiding implementation details
B. Cohesion is the OO principle most closely associated with making sure that classes know about other classes only through their APIs
C. Cohesion is the OO principle most closely associated with making sure that a class is designed with a single, well-focused purpose
D. Cohesion is the OO principle most closely associated with allowing a single object to be seen as having many types
Answer:
Answer C is correct.
A refers to encapsulation, B refers to coupling, and D refers to polymorphism.(Objective 5.1)


6. Given the following,
class X { void do1() { } }
class Y extends X { void do2() { } }

class Chrome {
  public static void main(String [] args) {
    X x1 = new X();
    X x2 = new Y();
    Y y1 = new Y();
    
    // insert code here
  }
}
Which, inserted at line 9, will compile? (Choose all that apply.)
A. x2.do2();
B. (Y)x2.do2();
C. ((Y)x2).do2();
D. None of the above statements will compile
Answer:
C is correct. Before you can invoke Y's do2 method you have to cast x2 to be of type Y. Statement B looks like a proper cast but without the second set of parentheses, the compiler thinks it's an incomplete statement.
A, B and D are incorrect based on the preceding.(Objective 5.2)


7. Given:
1. ClassA has a ClassD
2. Methods in ClassA use public methods in ClassB
3. Methods in ClassC use public methods in ClassA
4. Methods in ClassA use public variables in ClassB
Which is most likely true? (Choose the most likely.) A. ClassD has low cohesion
B. ClassA has weak encapsulation
C. ClassB has weak encapsulation
D. ClassB has strong encapsulation
E. ClassC is tightly coupled to ClassA
Answer:
C is correct. Generally speaking, public variables are a sign of weak encapsulation.
A, B, D, and E are incorrect, because based on the information given, none of these statements can be supported. (Objective 5.1)


8. Given:
class Dog {
  public void bark() { System.out.print("woof "); }
}
class Hound extends Dog {
  public void sniff() { System.out.print("sniff "); }
  public void bark() { System.out.print("howl "); }
}
public class DogShow {
  public static void main(String[] args) { new DogShow().go(); }
  void go() {
    new Hound().bark();
    ((Dog) new Hound()).bark();
    ((Dog) new Hound()).sniff();
  }
}
What is the result? (Choose all that apply.)
A. howl howl sniff
B. howl woof sniff
C. howl howl followed by an exception
D. howl woof followed by an exception
E. Compilation fails with an error at line 12
F. Compilation fails with an error at line 13
Answer:
F is correct. Class Dog doesn't have a sniff method.
A, B, C, D, and E are incorrect based on the above information. (Objective 5.2)


9. Given:
public class Redwood extends Tree {
   public static void main(String[] args) {
     new Redwood().go();
   }
   void go() {
     go2(new Tree(), new Redwood());
     go2((Redwood) new Tree(), new Redwood());
   }
   void go2(Tree t1, Redwood r1) {
     Redwood r2 = (Redwood)t1;
     Tree t2 = (Tree)r1;
   }
}
class Tree { }
What is the result? (Choose all that apply.)
A. An exception is thrown at runtime
B. The code compiles and runs with no output
C. Compilation fails with an error at line 6
D. Compilation fails with an error at line 7
E. Compilation fails with an error at line 10
F. Compilation fails with an error at line 11
Answer:
A is correct, a ClassCastException will be thrown when the code attempts to downcast a Tree to a Redwood.
B, C, D, E, and F are incorrect based on the above information.(Objective 5.2)


10. Given:
public class Tenor extends Singer {
   public static String sing() { return "fa"; }
   public static void main(String[] args) {
     Tenor t = new Tenor();
     Singer s = new Tenor();
     System.out.println(t.sing() + " " + s.sing());
   }
}
class Singer { public static String sing() { return "la"; } }
What is the result?
A. fa fa
B. fa la
C. la la
D. Compilation fails
E. An exception is thrown at runtime
Answer:
B is correct. The code is correct, but polymorphism doesn't apply to static methods.
A, C, D, and E are incorrect based on the above information.(Objective 5.2)


11. Given:
class Alpha {
  static String s = " ";
  protected Alpha() { s += "alpha "; }
}
class SubAlpha extends Alpha {
  private SubAlpha() { s += "sub "; }
}
public class SubSubAlpha extends Alpha {
  private SubSubAlpha() { s += "subsub "; }
  public static void main(String[] args) {
    new SubSubAlpha();
    System.out.println(s);
  }
}
What is the result? A. subsub
B. sub subsub
C. alpha subsub
D. alpha sub subsub
E. Compilation fails
F. An exception is thrown at runtime
Answer:
C is correct. Watch out, SubSubAlpha extends Alpha! Since the code doesn't attempt to make a SubAlpha, the private constructor in SubAlpha is okay.
A, B, D, E, and F are incorrect based on the above information. (Objective 5.3)


12. Given:
class Building {
   Building() { System.out.print("b "); }
   Building(String name) {
      this(); 
      System.out.print("bn " + name);
   }
}
public class House extends Building {
   House() { System.out.print("h "); }
   House(String name) {
      this(); 
      System.out.print("hn " + name);
   }
   public static void main(String[] args) { new House("x "); }
}
what is the result?
A. h hn x
B. hn x h
C. b h hn x
D. b hn x h
E. bn x h hn x
F. b bn x h hn x
G. bn x b h hn x
H. Compilation fails
Answer:
C is correct. Remember that constructors call their superclass constructors, which execute first, and that constructors can be overloaded.
A, B, D, E, F, G, and H are incorrect based on the above information.(Objectives 1.6, 5.4)


13. Given:
class Mammal {
String name = "furry ";
String makeNoise() { return "generic noise"; }
}
class Zebra extends Mammal {
String name = "stripes ";
String makeNoise() { return "bray"; }
}
public class ZooKeeper {
public static void main(String[] args) { new ZooKeeper().go(); }
void go() {
Mammal m = new Zebra();
System.out.println(m.name + m.makeNoise());
}
}
What is the result?
A. furry bray
B. stripes bray
C. furry generic noise
D. stripes generic noise
E. Compilation fails
F. An exception is thrown at runtime
Answer:
A is correct. Polymorphism is only for instance methods.
B, C, D, E, and F are incorrect based on the above information.(Objectives 1.5, 5.4)


14. You're designing a new online board game in which Floozels are a type of Jammers, Jammers can have Quizels, Quizels are a type of Klakker, and Floozels can have several Floozets. Which of the following fragments represent this design? (Choose all that apply.)
A.
import java.util.*;
interface Klakker { }
class Jammer { Set q; }
class Quizel implements Klakker { }
public class Floozel extends Jammer { List f; }
interface Floozet { }
B.
import java.util.*;
class Klakker { Set q; }
class Quizel extends Klakker { }
class Jammer { List f; }
class Floozet extends Floozel { }
public class Floozel { Set k; }
C.
import java.util.*;
class Floozet { }
class Quizel implements Klakker { }
class Jammer { List q; }
interface Klakker { }
class Floozel extends Jammer { List f; }
D.
import java.util.*;
interface Jammer extends Quizel { }
interface Klakker { }
interface Quizel extends Klakker { }
interface Floozel extends Jammer, Floozet { }
interface Floozet { }
Answer:
A and C are correct. The phrase "type of" indicates an "is-a" relationship (extends or implements), and the phrase “have” is of course a "has-a" relationship (usually instance variables).
B and D are incorrect based on the above information. (Objective 5.5)


15. Given:
class A { }

class B extends A { }

public class ComingThru {
  static String s = "-";
  
  public static void main(String[] args) {
  A[] aa = new A[2];
  B[] ba = new B[2];
  sifter(aa);
  sifter(ba);
  sifter(7);
  
  System.out.println(s);
  }
  
  static void sifter(A[]... a2) { s += "1"; }
  static void sifter(B[]... b1) { s += "2"; }
  static void sifter(B[] b1) { s += "3"; }
  static void sifter(Object o) { s += "4"; }
}
What is the result?
A. -124
B. -134
C. -424
D. -434
E. -444
F. Compilation fails
Answer:
D is correct. In general, overloaded var-args methods are chosen last. Remember that arrays are objects. Finally, an int can be boxed to an Integer and then "widened" to an Object.
A, B, C, E, and F are incorrect based on the above information.(Objective 1.5)



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

Monday, July 2, 2012

Java Standard Edition 6 Programmer Certified Professional Exam



OCPJ
     The Oracle Certified Professional, Java SE 6 Programmer exam is considered one of the hardest in the IT industry, and we can tell you from experience that a large chunk of exam candidates go in to the test unprepared. As programmers, we tend to learn only what we need to complete our current project, given the insane deadlines we're usually under But this exam attempts to prove your complete understanding of the Java language, not just the parts of it you've become familiar with in your work.
     It isn't enough to be able to get your code to work correctly; you must understand the core fundamentals in a deep way, and with enough breadth to cover virtually anything that could crop up in the course of using the language.
    The Oracle Certified Professional, Java SE 6 Programmer Exam (covered in the posts of my Blog) is unique to the IT certification realm, because it actually evaluates your skill as a developer rather than simply your knowledge of the language or tools. Becoming a Certified Java Developer is, by definition, a development experience.

 Who Cares About Certification?
    Employers do. Headhunters do. Programmers do. Java's programmer exam has been considered the fastest-growing certification in the IT world, and the number of candidates taking the exam continues to grow each year. Passing this exam proves three important things to a current or prospective employer: you're smart; you know how to study and prepare for a challenging test; and, most of all, you know the Java language.
    If an employer has a choice between a candidate who has passed the exam and one who hasn't, the employer knows that the certified programmer will be an assert to the Company.To really demonstrate your ability to develop (as opposed to just your knowledge of the language), you should consider pursuing the Developer Exam

If you Lost:
     If you don't pass the exam, don't be discouraged. Try to have a good attitude about the experience, and get ready to try again. Consider yourself a little more educated. You know the format of the test a little better, and the report shows which areas you need to strengthen.
     If you bounce back quickly, you'll probably remember several of the questions you might have missed. This will help you focus your study efforts in the right area. Ultimately, remember that Sun certifications are valuable because they're hard to get. After all, if anyone could get one, what value would it have? In the end, it takes a good attitude and a lot of studying, but you can do it!

What is we are going to Post?


     You will not find a beginner's guide to learning Java in this Blog. All posts of this blog are dedicated solely to helping you pass the exams. If you are brand new to Java, we suggest you spend a little time learning the basics. In other words, for any given topic, we start with the assumption that you are new to that topic. So we assume you're new to the individual topics, but we assume that you are not new to Java. We also do not pretend to be both preparing you for the exam and simultaneously making you a complete Java being. This is very clear about my mission.
     Before discussing about the practice questions we will post set of Drill Points. You also can use the drills as a way to do a quick cram before the exam.


regards,
M.Agni...,
Executive,
TalentSprint 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





AdSense