Wednesday 13 July 2016

Why postgresSQL?

Why postgresSQL?


PostgreSQL is capable of processing big data and which has better capabilities as follows.

LimitValue
Maximum Database SizeUnlimited
Maximum Table Size32 TB
Maximum Row Size1.6 TB
Maximum Field Size1 GB
Maximum Rows per Table Unlimited
Maximum Columns per Table250-1600 (Depending on Column types)
Maximum Indexes per Table?Unlimited

what is postgreSQL

What is postgreSQL?


PostgreSQL is a Relational Database Management System(RDBMS) is a named collection of SQL objects. It is a collection of schemas and the schemas contain the tables, functions, etc.
  • Databases are created with the CREATE DATABASE command and
  • Databases are destroyed with the DROP DATABASE command.
To determine the set of existing databases:
-SQL: SELECT datname FROM pg_database;
Above command will list all the databases
-psql META COMMAND: \l(backslash lowercase L)
Using \l also we can list all the databases

Tuesday 12 July 2016

How to check disk space in linux

Example:
[pgdb@localhost home]$ df -H
Filesystem             Size   Used  Avail Use% Mounted on
/dev/vda3              106G    12G    89G  12% /
tmpfs                   22G    78k    22G   1% /dev/shm
/dev/vda1              204M    34M   160M  18% /boot
/dev/vda2              201G   136G    55G  72% /data1
/dev/vda6              201G   402M   191G   1% /data2
172.19.1.25:/data/pub
                       316G   216G    84G  73% /nfs

How to check disk space of a folder?
Example:
[pgdb@localhost home]$ df -H /home
Filesystem             Size   Used  Avail Use% Mounted on
/dev/vda3              106G    12G    89G  12% /

Get more about df command using below?
df --help
or
man df

Thursday 7 July 2016

PostgreSQL Tutorial

Java Interview questions and answers part3

What is the result of below code?

Given the proper import statement(s), and
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("2");
pq.add("4");
System.out.print(pq.peek() + " ");
pq.offer("1");
pq.add("3");
pq.remove("1");
System.out.print(pq.poll() + " ");
if(pq.remove("2")) System.out.print(pq.poll() + " ");
System.out.println(pq.poll() + " " + pq.peek());

A. 2 2 3 3
B. 2 2 3 4
C. 4 3 3 4
D. 2 2 3 3 3
E. 4 3 3 3 3
F. 2 2 3 3 4
G. Compilation fails
H. An exception is thrown at runtime
Answer:
B is correct. For the sake of the exam, add() and offer() both add to (in this case),
naturally sorted queues. The calls to poll() both return and then remove the first item
from the queue, so the if test fails.

Question:
Given:
import java.util.*;
class Turtle {
int size;
public Turtle(int s) { size = s; }
public boolean equals(Object o) { return (this.size == ((Turtle)o).size); }
// insert code here
}
public class TurtleTest {
public static void main(String[] args) {
LinkedHashSet<Turtle> t = new LinkedHashSet<Turtle>();
t.add(new Turtle(1)); t.add(new Turtle(2)); t.add(new Turtle(1));
System.out.println(t.size());
}
}
And these two fragments:
I. public int hashCode() { return size/5; }
II. // no hashCode method declared
If fragment I or II is inserted, independently, at line 8, which are true? (Choose all that apply.)
A. If fragment I is inserted, the output is 2
B. If fragment I is inserted, the output is 3
C. If fragment II is inserted, the output is 2
D. If fragment II is inserted, the output is 3
E. If fragment I is inserted, compilation fails
F. If fragment II is inserted, compilation fails
Answer:
A and D are correct. While fragment II wouldn't fulfill the hashCode() contract (as you
can see by the results), it is legal Java. For the purpose of the exam, if you don’t override
hashCode(), every object will have a unique hashcode.

Which are true? (Choose all that apply.) Given the proper import statement(s), and:

TreeSet<String> s = new TreeSet<String>();
TreeSet<String> subs = new TreeSet<String>();
s.add("a"); s.add("b"); s.add("c"); s.add("d"); s.add("e");
subs = (TreeSet)s.subSet("b", true, "d", true);
s.add("g");
s.pollFirst();
s.pollFirst();
s.add("c2");
System.out.println(s.size() +" "+ subs.size());

A. The size of s is 4
B. The size of s is 5
C. The size of s is 7
D. The size of subs is 1
E. The size of subs is 2
F. The size of subs is 3
G. The size of subs is 4
H. An exception is thrown at runtime
Answer:
B and F are correct. After "g" is added, TreeSet s contains six elements and TreeSet subs
contains three (b, c, d), because "g" is out of the range of subs. The first pollFirst()
finds and removes only the "a". The second pollFirst() finds and removes the "b" from
both TreeSets (remember they are backed). The final add() is in range of both TreeSets.
The final contents are [c,c2,d,e,g] and [c,c2,d].

What is the output of below program? 
class Magellan {
public static void main(String[] args) {
TreeMap<String, String> myMap = new TreeMap<String, String>();
myMap.put("a", "apple"); myMap.put("d", "date");
myMap.put("f", "fig"); myMap.put("p", "pear");
System.out.println("1st after mango: " +myMap.higherKey("f"));
System.out.println("1st after mango: " + myMap.ceilingKey("g"));
System.out.println("1st after mango: " +myMap.floorKey("g"));
SortedMap<String, String> sub = new TreeMap<String, String>();
sub = myMap.tailMap("f");
System.out.println("1st after mango: " +sub.firstKey());
System.out.println("1st after mango: " + sub.lastKey());
System.out.println(sub.size());
}
}
Answer:
1st after mango: p
1st after mango: p
1st after mango: f
1st after mango: f
1st after mango: p
2

Which, inserted independently at line 9, will compile? (Choose all that apply.) 
import java.util.*;
class Business { }
class Hotel extends Business { }
class Inn extends Hotel { }
public class Travel {
ArrayList<Hotel> go() {
// insert code here
}
}

A. return new ArrayList<Inn>();
B. return new ArrayList<Hotel>();
C. return new ArrayList<Object>();
D. return new ArrayList<Business>();
Answer:
B is correct.
A is incorrect because polymorphic assignments don't apply to generic type parameters. C
and D are incorrect because they don't follow basic polymorphism rules.

What is the result? 
import java.util.*;
class Dog { int size; Dog(int s) { size = s; } }
public class FirstGrade {
public static void main(String[] args) {
TreeSet<Integer> i = new TreeSet<Integer>();
TreeSet<Dog> d = new TreeSet<Dog>();

d.add(new Dog(1)); d.add(new Dog(2)); d.add(new Dog(1));
i.add(1); i.add(2); i.add(1);
System.out.println(d.size() + " " + i.size());
}
}
A. 1 2
B. 2 2
C. 2 3
D. 3 2
E. 3 3
F. Compilation fails
G. An exception is thrown at runtime
Answer:
G is correct. Class Dog needs to implement Comparable in order for a TreeSet (which
keeps its elements sorted) to be able to contain Dog objects.

What is output of below program? 
class GeoCache {
public static void main(String[] args) {
String[] s = {"map", "pen", "marble", "key"};
Othello o = new Othello();
Arrays.sort(s,o);//perameters here String[] and class obj which should impliment Comparator
for(String s2: s) System.out.print(s2 + " ");
System.out.println(Arrays.binarySearch(s, "map"));//this method meake use of compareTo of Othello
}
static class Othello implements Comparator<String> {
public int compare(String a, String b) { return a.compareTo(b); }
}
}
Answer:
output:key map marble pen 1

What is output of below program? 
class GeoCache {
public static void main(String[] args) {
String[] s = {"map", "pen", "marble", "key"};
Othello o = new Othello();
Arrays.sort(s,o);//perameters here String[] and class obj which should impliment Comparator
for(String s2: s) System.out.print(s2 + " ");
System.out.println(Arrays.binarySearch(s, "map"));//this method meake use of compareTo of Othello
}
static class Othello implements Comparator<String> {
public int compare(String a, String b) { return b.compareTo(a); }//check difference here with previous question.
}
}
Answer:
output:pen marble map key -1

Which are true? (Choose all that apply.)
import java.util.*
public class GeoCache {
public static void main(String[] args) {
String[] s = {"map", "pen", "marble", "key"};
Othello o = new Othello();
Arrays.sort(s,o);
for(String s2: s) System.out.print(s2 + " ");
System.out.println(Arrays.binarySearch(s, "map"));
}
static class Othello implements Comparator<String> {
public int compare(String a, String b) { return b.compareTo(a); }
}
}

A. Compilation fails
B. The output will contain a 1
C. The output will contain a 2
D. The output will contain a –1
E. An exception is thrown at runtime
F. The output will contain "key map marble pen"
G. The output will contain "pen marble map key"
Answer:
D and G are correct. First, the compareTo() method will reverse the normal sort.
Second, the sort() is valid. Third, the binarySearch() gives –1 because it needs to be
invoked using the same Comparator (o), as was used to sort the array. Note that when the
binarySearch() returns an "undefined result" it doesn’t officially have to be a -1, but it
usually is, so if you selected only G, you get full credit!

Assume you have a class that holds two private variables: a and b. Which of the following pairs can prevent concurrent access problems in that class? (Choose all that apply.) 
A. public int read(){return a+b;}
public void set(int a, int b){this.a=a;this.b=b;}
B. public synchronized int read(){return a+b;}
public synchronized void set(int a, int b){this.a=a;this.b=b;}
C. public int read(){synchronized(a){return a+b;}}
public void set(int a, int b){synchronized(a){this.a=a;this.b=b;}}
D. public int read(){synchronized(a){return a+b;}}
public void set(int a, int b){synchronized(b){this.a=a;this.b=b;}}
E. public synchronized(this) int read(){return a+b;}
public synchronized(this) void set(int a, int b){this.a=a;this.b=b;}
F. public int read(){synchronized(this){return a+b;}}
public void set(int a, int b){synchronized(this){this.a=a;this.b=b;}}
Answer:
B and F are correct. By marking the methods as synchronized, the threads will get the
lock of the this object before proceeding. Only one thread will be setting or reading at any
given moment, thereby assuring that read() always returns the addition of a valid pair.
Wrong:
A is incorrect because it is not synchronized; therefore, there is no guarantee that the values
added by the read() method belong to the same pair. C and D are incorrect; only objects
can be used to synchronize on. E fails —it is not possible to select other objects (even this)
to synchronize on when declaring a method as synchronized.

Choose Appropriate option? Given:
public class TwoThreads {
static Thread laurel, hardy;
public static void main(String[] args) {
laurel = new Thread() {
public void run() {
System.out.println("A");
try {
hardy.sleep(1000);
} catch (Exception e) {
System.out.println("B");
}
System.out.println("C");
}
};
hardy = new Thread() {
public void run() {
System.out.println("D");
try {
laurel.wait();
} catch (Exception e) {
System.out.println("E");
}
System.out.println("F");
}
};
laurel.start();
hardy.start();
}
}
Which letters will eventually appear somewhere in the output? (Choose all that apply.)
A. A
B. B
C. C
D. D
E. E
F. F
G. The answer cannot be reliably determined
H. The code does not compile
Answer:
A, C, D, E, and F are correct. This may look like laurel and hardy are battling to cause
the other to sleep() or wait()—but that's not the case. Since sleep() is a static
method, it affects the current thread, which is laurel (even though the method is invoked
using a reference to hardy). That's misleading but perfectly legal, and the Thread laurel
is able to sleep with no exception, printing A and C (after at least a 1-second delay). Meanwhile
hardy tries to call laurel.wait()—but hardy has not synchronized on laurel,
so calling laurel.wait() immediately causes an IllegalMonitorStateException, and
so hardy prints D, E, and F. Although the order of the output is somewhat indeterminate
(we have no way of knowing whether A is printed before D, for example) it is guaranteed
that A, C, D, E, and F will all be printed in some order, eventually—so G is incorrect.

Will below code compiles?  
class A1 {
int a=10;
static int  add(int i, int j){
return i+j;
}
  }
class B1 extends A1{
int a=10;
public static void main(String argv[]){
short s = 9;
System.out.println(add(s,6)+" "+super.a);//error becoz of super key word.
}
   }
Answer:
error bcoz of "super" key word.We can not use "this" and "super" key word in side static methods and blocks(Cannot use this(or)super in a static context)

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: