Friday 19 July 2013

OCJP Model Question and Answer - Inheritence ,Constructor

Question:

 class Atom {
 Atom() { System.out.print("atom "); }
 }
 class Rock extends Atom {
 Rock(String type) { System.out.print(type); }
 }
 public class Mountain extends Rock {
 Mountain() {
 super("granite ");
 new Rock("granite ");
 }
 public static void main(String[] a) { new Mountain(); }
 }

What is the result?

A. Compilation fails.
B. atom granite
C. granite granite
D. atom granite granite
E. An exception is thrown at runtime.
F. atom granite atom granite


Concepts to know:

Whenever an object is created for a child class , its constructor should be executed.But the order of
execution of constructors in case of inheritance will be ,

Default Constructor of parent is executed first and then default constructor of the child in the hierarchy tree.


Hence here ,

Hierarchy--   Atom


                     Rock


                    Mountain

Hence when object for Mountain is created  , order of execution of methods are as follows,

Atom() { System.out.print("atom "); }                                                                                                                        --   o/p      atom

Rock()

Mountain()
{
  super("granite");       // will call Rock(String type) hence yields  
                                                                   -- o/p       granite

  new Rock("granite ");  // will call  Atom() { System.out.print("atom "); }
                                                                   --   o/p        atom     ,then calls
            // Rock(String type)                        --  o/p granite

                         
 }


Ans : (F)  atom granite atom granite

OCJP Model Question and Answer - Concept Java Generics

Question 6:

 public class Score implements Comparable<Score> {
 private int wins, losses;
 public Score(int w, int l) { wins = w; losses = l; }
 public int getWins() { return wins; }
 public int getLosses() { return losses; }
 public String toString() {
 return "<" + wins + "," + losses + ">";
 }
 // insert code here
 }

Which method will complete this class?
A. public int compareTo(Object o){/*more code here*/}
B. public int compareTo(Score other){/*more code here*/}
C. public int compare(Score s1,Score s2){/*more code here*/}
D. public int compare(Object o1,Object o2){/*more code here*/}

Things to know :
..............................

java generics concept.

Explanation :
.........................

It comes under the generics concept.
when you try with  public int compareTo(Object o){/*more code here*/} ,
you will come across the following error.
Name clash: The method compareTo(Object) of type Score has the same erasure as compareTo(T) of type Comparable<T> but does not override it


Since given the comparable operates on score , one should use Score type.

hence the answer is option B

-----------------------------------------------------------------------------------------------------------------------------------

Question : 7
....................

11. class Converter {
12. public static void main(String[] args) {
13. Integer i = args[0];
14. int j = 12;
15. System.out.println("It is " + (j==i) + " that j==i.");
16. }
17. }


What is the result when the programmer attempts to compile the code and run it with the
command java Converter 12?


A. It is true that j==i.
B. It is false that j==i.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 13.



Explanation:
.......................
compilation fails. with the error
Type mismatch: cannot convert from String to Integer on line no 13

Ans: D

------------------------------------------------------------------------------------------------------------------------------------

Question : 8  
....................

5. import java.util.Date;
6. import java.text.DateFormat;
21. DateFormat df;
22. Date date = new Date();
23. // insert code here
24. String s = df.format(date);

Which code fragment, inserted at line 23, allows the code to compile?

A. df = new DateFormat();
B. df = Date.getFormat();
C. df = date.getFormat();
D. df = DateFormat.getFormat();
E. df = DateFormat.getInstance();


Explanation:
........................

A.Error  : Cannot instantiate the type DateFormat
B.Error  : The method getFormat() is undefined for the type Date
C.Error  : The method getFormat() is undefined for the type Date
D.Error  : The method getFormat() is undefined for the type DateFormat
E. works fine

Ans : E



Please find more in the following posts.

Please feel free to comment.

OCJP - Oracle Certified Java Professional Model Question and Answers with Solutions -- OCJP solved

OCJP - Oracle Certified Java Professional Model Question and Answers with Solutions.

          You can find here, some model OCJP question and answers with its explanation.Hope it will be useful to you all.


Question :1
......................

22. StringBuilder sb1 = new StringBuilder("123");
23. String s1 = "123";
24. // insert code here
25. System.out.println(sb1 + " " + s1);

Which code fragment, inserted at line 24, outputs "123abc 123abc"?


A. sb1.append("abc"); s1.append("abc");
B. sb1.append("abc"); s1.concat("abc");
C. sb1.concat("abc"); s1.append("abc");
D. sb1.concat("abc"); s1.concat("abc");
E. sb1.append("abc"); s1 = s1.concat("abc");
F. sb1.concat("abc"); s1 = s1.concat("abc");
G. sb1.append("abc"); s1 = s1 + s1.concat("abc");
H. sb1.concat("abc"); s1 = s1 + s1.concat("abc");



Explanation :
.............................

Things to know :

String class  - Immutable

StringBuffer  - mutable (thread safe)

StringBuilder - mutable , not synchronized (not thread safe)


Example to understand :
............................................

public class exam17 {

    public static void main ( String args [])
    {
        StringBuilder sb1 = new StringBuilder("abc");
        String s = "abc";
       
        String s1 = "abc";
       
        sb1 = sb1.append("123");
       
        s=s.concat("123");
       
        s1.concat ("123");
       
        System.out.println(sb1 + "    " + s + "       " + s1);
       
    }
}


output :
..................
abc123    abc123       abc


since string objects are immutable , we can witness that s1 contains value 'abc'.

Note : variable s1 is introduced for example purpose to show string objects are immutable



hence the answer is option (E)


---------------------------------------------------------------------------------------------------------------------

Question : 2

Inner Class and Accessing its objects
.....................................................................

class Line {
 public class Point { public int x,y;}
 public Point getPoint() { return new Point(); }
 }
 class Triangle {
 public Triangle() {
 // insert code here
 }
 }
Which code, inserted at line 16, correctly retrieves a local instance of a Point object?
A. Point p = Line.getPoint();
B. Line.Point p = Line.getPoint();
C. Point p = (new Line()).getPoint();
D. Line.Point p = (new Line()).getPoint();


Concept to know :
...................................
 Inner class and how it inherits the features of outer class


Example program :
..................................

public class outerclass {

    public class innerclass
    {
        public void innermethod ()
        {   System.out.println("innermethod accessed");}
   
    }
   
    public static void main (String args[])
    {
        innerclass obj1 = new innerclass(); // note this is wrong way to create objects of inner class
             
               // Error faced : No enclosing instance of type outerclass is accessible. Must qualify the allocation with an enclosing instance of type outerclass (e.g. x.new A() where x is an instance of outerclass).

               
            outerclass obj1 = new outerclass();
      
            outerclass.innerclass obj2 = obj1.new innerclass();
      
            obj2.innermethod();
          

    }
   
   
}


Ans : D) Line.Point p = (new Line()).getPoint();  -- first object of outer class is created then the innerclass methods are accessed.

-------------------------------------------------------------------------------------------------------------------------------



Question : 3  

Array declaration
...........................

Which two code fragments correctly create and initialize a static array of int elements? (Choose
two.)
A. static final int[] a = { 100,200 };
B. static final int[] a;
static { a=new int[2]; a[0]=100; a[1]=200; }
C. static final int[] a = new int[2]{ 100,200 };
D. static final int[] a;
static void init() { a = new int[3]; a[0]=100; a[1]=200; }


Explanation:

............................
More-often questions like this can be solved by analysing the options.

A. Error faced : Illegal modifier for parameter a; only final is permitted

B. Error faced : Illegal modifier for parameter a; only final is permitted

C. Error faced : Cannot define dimension expressions when an array initializer is provided

D. same error as A  for first line and

  second line  error is given as : Syntax error on token(s), misplaced construct(s)

Please give your idea, since i found error on all options





 ----------------------------------------------------------------------------------------------------------------------------------



Question :4


Array Index and its accessing its element:
...............................................................

 class Alligator {
 public static void main(String[] args) {
 int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}};
 int [][]y = x;
 System.out.println(y[2][1]);
 }
 }
What is the result?

A. 2
B. 3
C. 4
D. 6
E. 7
F. Compilation fails.

Explanation :
...........................

This is very simple.As we know array index starts with 0 hence  y[2][1] will yield  3rd records 2nd
element . Hence 7 is the output

Ans: 7 


-----------------------------------------------------------------------------------------------
 

Question : 5

.............................

Given that the current directory is empty, and that the user has read and write permissions, and
the following:

 import java.io.*;
 public class DOS {
 public static void main(String[] args) {
 File dir = new File("dir");
 dir.mkdir();
 File f1 = new File(dir, "f1.txt");
 try {
 f1.createNewFile();
 } catch (IOException e) { ; }
 File newDir = new File("newDir");
 dir.renameTo(newDir);
 }
 }

Which statement is true?

A. Compilation fails.
B. The file system has a new empty directory named dir.
C. The file system has a new empty directory named newDir.
D. The file system has a directory named dir, containing a file f1.txt.
E. The file system has a directory named newDir, containing a file f1.txt.



Explanation :
........................

so , f1.txt will be created under 'dir' directory , but then  the 'dir' directory is renamed to newDir.

Now the f1.txt is present under newDir directory.

Answer:E














..................

Please find more questions in the updated posts.


The answers are correct to my perspective.Please feel free to post your comments.

Thursday 8 November 2012

Is a partition resizeable ? / How to create a partition that can be extended in size ?


RHCE exercise : Is a partition resizeable ? / How to create a partition that can be extended in size in linux ?

Since i am an open source guy, i will explain to you , how to do this in linux.

This can be done using a concept called Logical Volume Management (LVM).

  We will go step by step for this,
 For this exercise,there are two main steps
Ø  Creating a lvm partition.

Ø  Resizing the partition.

Creating a lvm partition

1.First , one should create a partition of type lvm.Here are the steps below,
            fdisk  /dev/sda (your partition name)
               then choose n (to create new partition)
              give the size ..
              then choose  t (type of partition)
              select 8e which is a lvm partition.
Restart the system.

2.Now the partition is ready for lvm creation.
           There are three commands that needs to be performed.
                   Pvcreate  à physical volume creation
                  Vgcreate   à volume group creation
                  Lvcreate    à logical volume creation

The execution of the above commands are done  as follows,




Here note : /dev/sda3 is the targeted lvm partition.

3.Now the lvm partition is created.Makesure you format it and then mount it.Find the screenshot below for your reference.


          The partition is formatted using
                              Mkfs.ext4  /dev/vg005/lv005
                              Where vg005 – volume group name
                                           Lv005  - logical volume name
         Then the partition is mounted in /lvm  directory.



Resizing the partition
4.Now the lvm partition created can be resized.

         Extending the partition size (lvextend)
             1. Logical volume extend command.(lvextend).
            2.Check partition for any disk errors.
            3.Resize filesystem to the desired size.
       Find the screen shot below for the exact procedure.


 
.
You can see a Lvsize is 52 MB in 6th line.Then the lvextend is done and the size gets to 152 MB which is highlighted.
Note: This is no magic, the lv partition should be created large enough during partitioning ,so that makes  future size extentions possible.

     Reducing the partition size(lvreduce)
                         1.unmount the partition.
                         2.Check partition for any disk errors.
                         3. Resize filesystem to the desired size.
                         4.Logical volume reduce (lvreduce)
       Find the screen shot below for the exact procedure.





Here note the previously extended paritition (ie) 152 MB is reduced to 52 MB.

This is how a partition can be resized .Give a try by yourself .. Enjoy !!
 


Related Posts Plugin for WordPress, Blogger...