Thursday 7 July 2016

Java interview questions and answers part2


Will below code compiles successfully? 
public class Test {
class T{
static final String af="20";
static final void m1() {
}
}
}
Answer:
error at method m1: The method m1 cannot be declared static; static methods can only be declared in a static or top level type

Will below code compiles successfully? 
public class Test {
final class T{
static final String af="20";
static final void m1() {
}
}
}
Answer:
error at method m1: The method m1 cannot be declared static; static methods can only be declared in a static or top level type

note:
variable level final is considered as highest priority than static.
method level static is considered as highest priority than final shown in above example.
final methods will not allow to create static variables inside method but can access static variables.
static methods will allow to create final variable inside method.

Will below code compiles successfully? 
public static class TestSuper {//error:Illegal modifier for the class TestSuper; only public, abstract & final are permitted
}
note:top level classes will not allow protected,private
note1: inner classes allows protected,private,static also where top level class wont.

Will below code compiles successfully? 
public class TestInnerClass {
private static String name="ramu";
static class Inner{
void m1(){
System.out.println("private name is:"+name);
}
}

public static void main(String args[]) {
TestInnerClass.Inner inner = new TestInnerClass.Inner();
System.out.println(inner.m1());//error:The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
}
}
Answer: compilation will fails in above progaram because println(void) overloaded method is not there.

Will below code compiles successfully? 

public class CurrentClassVarsAndSubclassMet {
String _="sudo";
public static void main(String args[]){
SuperClass superClassObj = new SubClass();
superClassObj.m1();
System.out.println(superClassObj.$);
}
}
class SuperClass {
String $="king";
void m1(){
System.out.println("inside superClass");
}
}
class SubClass extends SuperClass{
String $="Queen";
void m1(){
System.out.println("inside subClass");
}
}
Answer:
output:
inside subClass
king

Will below code compiles successfully? 

public class CurrentClassVarsAndSubclassMet {
    String _="sudo";
public static void main(String args[]){
SuperClass superClassObj = new SubClass();
superClassObj.m2();
System.out.println(superClassObj.$);
}
}
class SuperClass {
String $="king";
void m1(){
System.out.println("inside superClass");
}
}
class SubClass extends SuperClass{
String $="Queen";
void m2(){
System.out.println("inside subClass");
}
}
Answer: error at superClassObj.m2()  : The method m2() is undefined for the type SuperClass

Will below code compiles successfully? 

 public class CurrentClassVarsAndSubclassMet {
String _="sudo";
public static void main(String args[]){
SuperClass superClassObj = new SubClass();
superClassObj.m1();
System.out.println(superClassObj.$);
}
}
class SuperClass {
//String $="king";
void m1(){
System.out.println("inside superClass");
}
}
class SubClass extends SuperClass{
String $="Queen";
void m1(){
System.out.println("inside subClass");
}
}
Answer:Compilation fails.gives error at  System.out.println(superClassObj.$);"$ cannot be resolved or is not a field"

Inner Class Notes:
Note1: An inner class instance can never stand alone without a direct relationship to an instance of the outer class.
Note2: You can access the inner class through alive instance of outer class.
Note3: Inner class can access private members of the ourter class.

Will below code compiles and runs successfully? 

public class TestInnerClass {
private static String name="ramu";
static class Inner{
static void m1(){
System.out.println("private name is:"+name);
}
}
public static void main(String args[]) {
TestInnerClass.Inner.m1();
}
}
Answer:no error
output:private name is:ramu

Will below code compiles and runs successfully? 
public class TestInnerClass {
private static String name="ramu";
static class Inner{
 void m1(){
System.out.println("private name is:"+name);
}
}
public static void main(String args[]) {
TestInnerClass.Inner inner = new TestInnerClass.Inner();
inner.m1();
}
}
Answer:no error
output:private name is:ramu

Will below code compiles and runs successfully? 
public class TestInnerClass {
private static String name="ramu";
 class Inner{
 void m1(){
System.out.println("private name is:"+name);
}
}
public static void main(String args[]) {
TestInnerClass testInnerClass = new TestInnerClass();
TestInnerClass.Inner inner = testInnerClass.new Inner();
inner.m1();
}
}
Answer:no error
output:private name is:ramu

Will below code compiles and runs successfully? 
public class TestInnerClass {
private static String name="ramu";
static class Inner{
static void m1(){//here with static and without
System.out.println("private name is:"+name);
}
}
public static void main(String args[]) {
TestInnerClass testInnerClass = new TestInnerClass();
TestInnerClass.Inner inner = testInnerClass.new Inner();//error
inner.m1();
}
}
Answer:error :Illegal enclosing instance specification for type TestInnerClass.Inner

Will below code compiles and runs successfully? 
public class TestInnerClass {
private static String name="ramu";
 class Inner{
private void m1(){
System.out.println("private name is:"+name);
}
}
public static void main(String args[]) {
TestInnerClass testInnerClass = new TestInnerClass();
TestInnerClass.Inner inner = testInnerClass.new Inner();
inner.m1();
}
}
Answer:no error
output:private name is:ramu
Note:Private members of inner class can be access in outer class or top level class but not out side the class.

Will below code compiles and runs successfully? 

public class TestInnerClass {
private static String name="ramu";
 class Inner{
private void m1(){
System.out.println("private name is:"+name);
}
}
}
public class AccessTestInner {
public static void main(String args[]) {
TestInnerClass testInnerClass = new TestInnerClass();
TestInnerClass.Inner inner = testInnerClass.new Inner();
inner.m1();//error
}
}
Answer: error
output:error:The method m1() from the type TestInnerClass.Inner is not visible

What is output of below program? 
enum Foo
{
    BAR("bar"),
    BAZ("baz"),
    BAM("bam");
    private final String description;
    private Foo(String description)
    {
        this.description = description;
    }
    public String getDescription()
    {
        return description;
    }
    public static void main(String args[]){
     System.out.println(Foo.BAR.getDescription());
    }
}
Answer:
output:bar

What is output of below program?
abstract class Foo
{
    public static final String BAR = "bar";
    public static final String BAZ = "baz";
    public static final String BAM = "bam";

    public static void main(String args[]){
     System.out.println(Foo.BAR);
    }
}
Answer:
output:bar

What is output of below program?

enum Foo
{
    BAR,
    BAZ,
    BAM;
   public static void main(String args[]){
   System.out.println(BAR);
   }
}
Answer:
output:BAR

Will below code compiles and runs successfully?   
enum Currency {
PENNY(1), NICKLE(5), DIME(10), QUARTER(25)
}
Answer:Error:The constructor Currency(int) is undefined.

What is output of below program?

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}
Answer:
If you run Planet.class from the command line with an argument of 175, you get this output:
$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

Question: True or false: an Enum type can be a subclass of java.lang.String.
Answer: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
Which, inserted independently at line 6, will compile? (Choose all that apply.)
1. class Voop {
2. public static void main(String [] args) {
3. doStuff(1);
4. doStuff(1,2);
5. }
6. // insert code here
7. }

A.static void doStuff(int... doArgs) { }
B.static void doStuff(int[] doArgs) { }
C.static void doStuff(int doArgs...) { }
D.static void doStuff(int... doArgs, int y) { }
E.static void doStuff(int x, int... doArgs) { }
Answer: A,E

What is the result?

  1. public class AccessTestInner {
  2. static void doStuff(int... aa,int y){
  3. }
  4. public static void main(String args[]){
  5. doStuff(1);
  6. doStuff(1,2);
  7. }
  8. }
Answer: error at line 2: The variable argument type int of the method doStuff must be the last parameter
error at line 6:The method doStuff(int[], int) in the type AccessTestInner is not applicable for the arguments (int)
error at line 7:The method doStuff(int[], int) in the type AccessTestInner is not applicable for the arguments (int, int)

What is the result?

  1.  enum Animals {
  2.  DOG("woof"), CAT("meow"), FISH("burble");
  3.  String sound;
  4.  Animals(String s) { sound = s; }
  5.  }
  6.  class TestEnum {
  7.  static Animals a;
  8.  public static void main(String [] args) {
  9.  System.out.println(a.DOG.sound + " " + a.FISH.sound);
  10.  }
A.woof burble
B.Multiple compilation errors
C.Compilation fails due to an error on line 2
D.Compilation fails due to an error on line 3
E.Compilation fails due to an error on line 4
F.Compilation fails due to an error on line 9
Answer: A

What is the result? (Choose all that apply.)
Given two files:
1. package pkgA;
2. public class Foo {
3. int a = 5;
4. protected int b = 6;
5. public int c = 7;
6. }
3. package pkgB;
4. import pkgA.*;
5. public class Baz {
6. public static void main(String[] args) {
7. Foo f = new Foo();
8. System.out.print(" " + f.a);
9. System.out.print(" " + f.b);
10. System.out.print(" " + f.c);
11. }
12. }

A.5 6 7
B.5 followed by an exception
C.Compilation fails with an error on line 7
D.Compilation fails with an error on line 8
E.Compilation fails with an error on line 9
F.Compilation fails with an error on line 10
Answer: D,E

What is the result? (Choose all that apply.)
Given:
1. public class Electronic implements Device{ public void doIt() { } }
2.
3. abstract class Phone1 extends Electronic { }
4.
5. abstract class Phone2 extends Electronic{ public void doIt(int x) { } }
6.
7. class Phone3 extends Electronic implements Device{ public void doStuff() { } }
8.
9. interface Device { public void doIt(); }

A.Compilation succeeds
B.Compilation fails with an error on line 1
C.Compilation fails with an error on line 3
D.Compilation fails with an error on line 5
E.Compilation fails with an error on line 7
F.Compilation fails with an error on line 9
Answer: A

What is the result? (Choose all that apply.)
Given:
4. class Announce {
5. public static void main(String[] args) {
6. for(int __x = 0; __x < 3; __x++) ;
7. int #lb = 7;
8. long [] x [5];
9. Boolean []ba[];
10. enum Traffic { RED, YELLOW, GREEN };
11. }
12. }

A.Compilation succeeds
B.Compilation fails with an error on line 6
C.Compilation fails with an error on line 7
D.Compilation fails with an error on line 8
E.Compilation fails with an error on line 9
F.Compilation fails with an error on line 10
Answer: C, D and F are correct. Variable names cannot begin with a #, an array declaration can’t
include a size without an instantiation, and enums can’t be declared within a method

What is the result?
Given:
4. public class Frodo extends Hobbit {
5. public static void main(String[] args) {
6. Short myGold = 7;
7. System.out.println(countGold(myGold, 6));
8. }
9. }
10. class Hobbit {
11. int countGold(int x, int y) { return x + y; }
12. }

A.13
B.Compilation fails due to multiple errors
C.Compilation fails due to an error on line 6
D.Compilation fails due to an error on line 7
E.Compilation fails due to an error on line 11
Answer: D is correct. The Short myGold
is autoboxed correctly, but the countGold() method
cannot be invoked from a static context.

What is the result?
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(" ");
} }

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.

What is the result?
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();
} }


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.

Which, inserted at line 9, will compile? (Choose all that apply.)
Given the following,
1. class X { void do1() { } }
2. class Y extends X { void do2() { } }
3.
4. class Chrome {
5. public static void main(String [] args) {
6. X x1 = new X();
7. X x2 = new Y();
8. Y y1 = new Y();
9. // insert code here
10. }
11. }

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.

What is the result? (Choose all that apply.)
Given:
3. class Dog {
4. public void bark() { System.out.print("woof "); }
5. }
6. class Hound extends Dog {
7. public void sniff() { System.out.print("sniff "); }
8. public void bark() { System.out.print("howl "); }
9. }
10. public class DogShow {
11. public static void main(String[] args) { new DogShow().go(); }
12. void go() {
13. new Hound().bark();
14. ((Dog) new Hound()).bark();
15. ((Dog) new Hound()).sniff();
16. }
17. }

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 14
F.Compilation fails with an error at line 15
Answer: F is correct. Class Dog doesn’t have a sniff method.

What is the result?
public class CurrentClassVarsAndSubclassMet {
public static void main(String args[]){
go();
}
static void go() {
 new SubClass().bark();
((SuperClass) new SubClass()).bark();
//((SuperClass) new SubClass()).sniff(); with this error will come
}
}
class SuperClass {
public void bark() { System.out.print("woof "); }
}
class SubClass extends SuperClass{
public void sniff() { System.out.print("sniff "); }
 public void bark() { System.out.print("howl "); }
}
Answer:howl howl

What is the result? (Choose all that apply.)
Given:
3. public class Redwood extends Tree {
4. public static void main(String[] args) {
5. new Redwood().go();
6. }
7. void go() {
8. go2(new Tree(), new Redwood());
9. go2((Redwood) new Tree(), new Redwood());
10. }
11. void go2(Tree t1, Redwood r1) {
12. Redwood r2 = (Redwood)t1;
13. Tree t2 = (Tree)r1;
14. }
15. }
16. class Tree { }

A.An exception is thrown at runtime
B.The code compiles and runs with no output
C.Compilation fails with an error at line 8
D.Compilation fails with an error at line 9
E.Compilation fails with an error at line 12
F.Compilation fails with an error at line 13
Answer: A is correct, a ClassCastException will be thrown when the code attempts to downcast a
Tree to a Redwood.

What is the result?
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"; } }

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.

What is the result?

  1. class SuperClass {
  2. public static void bark() { System.out.print("woof "); }
  3. }
  4. class SubClass extends SuperClass{
  5. public void sniff() { System.out.print("sniff "); }
  6.  public void bark() { System.out.print("howl "); }
  7. }
Answer: error at line 7:This instance method cannot override the static method from SuperClass

What is the result?
public class CurrentClassVarsAndSubclassMet {
public static void main(String args[]){
go();
}
static void go() {
SuperClass s =new SubClass();
System.out.println(s.$);
s.bark();
}
}
class SuperClass {
static String $="super damu";
public static void bark() { System.out.print("woof "); }
}
class SubClass extends SuperClass{
static String $="sub damu";
public void sniff() { System.out.print("sniff "); }
 public static void bark() { System.out.print("howl "); }
}
Ans:super damu
woof
note: polymorphism not applicable for static mothods.

What is the result?

  1. class SuperClass {
  2. public void bark() { System.out.print("woof "); }
  3. }
  4. class SubClass extends SuperClass{
  5. public void sniff() { System.out.print("sniff "); }
  6.  public static void bark() { System.out.print("howl "); }
  7. }
Answer:
error at line 6 : This static method cannot hide the instance method from SuperClass

What is the result?
class AA { }
 class B extends AA { }
  class ComingThru {
 static String s = "-";
 public static void main(String[] args) {
 AA[] aa = new AA[2];
 B[] ba = new B[2];
sifter(aa);
 sifter(ba);
 sifter(7);
 System.out.println(s);
 }
 static void sifter(AA[]... a2) { s += "1"; }
 static void sifter(B[]... b1) { s += "2"; }
 static void sifter(B[] b1) { s += "3"; }
 static void sifter(Object o) { s += "4"; }
 }

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.

What is the result?
Given:
1. class Dims {
2. public static void main(String[] args) {
3. int[][] a = {{1,2,}, {3,4}};
4. int[] b = (int[]) a[1];
5. Object o1 = a;
6. int[][] a2 = (int[][]) o1;
7. int[] b2 = (int[]) o1;
8. System.out.println(b[1]);
9. } }

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 6 because o1 refers to an int[][]not an int[].
If line 6 was removed, the output would be 4

What is the result?
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));
} }
Answer:
Compilation fails short----->int is possible but int -----> short does not.

What is the result?
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 ");
}
}

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.

What is the result?
class Bridge {
   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.getValue(3));
   System.out.println(Suits.SPADES + " " + Suits.SPADES.points);
   System.out.println(Suits.values());
   }
   }
Answer:
output:
100
SPADES 30
[Ltest.com.Bridge$Suits;@5483cd

What is the result? (Choose all that apply.)
Given two files:
1. package pkgA;
2. public class Foo {
3. int a = 5;
4. protected int b = 6;
5. }
1. package pkgB;
2. import pkgA.*;
3. public class Fiz extends Foo {
4. public static void main(String[] args) {
5. Foo f = new Foo();
6. System.out.print(" " + f.a);
7. System.out.print(" " + f.b);
8. System.out.print(" " + new Fiz().a);
9. System.out.println(" " + new Fiz().b);
10. }
11. }

A. 5 6 5 6
B. 5 6 followed by an exception
C. Compilation fails with an error on line 6
D. Compilation fails with an error on line 7
E. Compilation fails with an error on line 8
F. Compilation fails with an error on line 9
Answer:
C, D, and E are correct. Variable a (default access) cannot be accessed from outside the
package. Since variable b is protected, it can be accessed only through inheritance.

What is the result? (Choose all that apply.):
3. class SubException extends Exception { }
4. class SubSubException extends SubException { }
5.
6. public class CC { void doStuff() throws SubException { } }
7.
8. class CC2 extends CC { void doStuff() throws SubSubException { } }
9.
10. class CC3 extends CC { void doStuff() throws Exception { } }
11.
12. class CC4 extends CC { void doStuff(int x) throws Exception { } }
13.
14. class CC5 extends CC { void doStuff() { } }

A. Compilation succeeds
B. Compilation fails due to an error on line 8
C. Compilation fails due to an error on line 10
D. Compilation fails due to an error on line 12
E. Compilation fails due to an error on line 14
Answer:
C is correct. An overriding method cannot throw a broader exception than the method it's
overriding. Class CC4's method is an overload, not an override.

What is the result? 
 class Ebb {
      static int x = 7;
      public static void main(String[] args) {
     String s = "";
    for(int y = 0; y < 3; y++) {
     x++;
     System.out.println(x);
     switch(x) {
      case 8: s += "8 ";
      case 9: s += "9 ";
      case 10:  s+= "10 ";
      case 13: s+= "13 ";
      case 14: s+= "14 ";
      default: s += "d ";
      }
     }
      System.out.println(s);
      }
      static { x++; }
      }
Answer:
9
10
11
9 10 13 14 d 10 13 14 d d

Question:
class MyException extends Exception { }
      class Tire {
      void doStuff() { }
     }
      class Retread extends Tire {
     public static void main(String[] args) {
      new Retread().doStuff();//Error:handle exception
     }
     void doStuff() throws MyException{//error:Exception MyException is not compatible with throws clause in Tire.doStuff()
      // insert code here
      System.out.println(7/0);
     }
     }
Answer:
Error:Exception MyException is not compatible with throws clause in Tire.doStuff()

Question:
class MyException extends Exception { }
      class Tire {
      void doStuff() { }
     }
      class Retread extends Tire {
     public static void main(String[] args) {
      new Retread().doStuff();//Error:handle exception
     }
     void doStuff() throws Exception{//error:Exception Exception is not compatible with throws clause in Tire.doStuff()
      // insert code here
      System.out.println(7/0);
     }
     }
Answer:
Error:Exception Exception is not compatible with throws clause in Tire.doStuff()

What is the result?
class MyException extends Exception { }
      class Tire {
      void doStuff() { }
     }
      class Retread extends Tire {
     public static void main(String[] args) {
      //new Retread().doStuff();//Error:handle exception
     }
     void doStuff() throws ArithmeticException{//error:no error
      // insert code here
      System.out.println(7/0);
     }
     }
Answer:
no error.if we use RuntimeException or sub exception in place of "ArithmeticException" no error if we use "Exception" error will come.

What is the result?
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

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.

What is the result?
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 ) { }
}
}

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.

Which of the following will be included in the output String s? (Choose all that apply.)
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);
} }

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)

What is the result? (Choose all that apply.)
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"); }
}
}

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.

Which are true? (Choose all that apply.)
 class TestSer {
     public static void main(String[] args) {
     SpecialSerial s = new SpecialSerial();
     try {
     ObjectOutputStream os = new ObjectOutputStream(
     new FileOutputStream("myFile.txt"));
     os.writeObject(s); os.close();
     System.out.print(++s.z + " ");
     ObjectInputStream is = new ObjectInputStream(
     new FileInputStream("myFile.txt"));
     SpecialSerial s2 = (SpecialSerial)is.readObject();
     is.close();
     System.out.println(s2.y + " " + s2.z);
     } catch (Exception x) {x.printStackTrace(); }
     }
     }
     class SpecialSerial implements Serializable {
     transient int y = 7;
     static int z = 9;
     }

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.

Also see:

No comments:

Post a Comment