Thursday, January 24, 2013

OCJP Tutorials - 7

                                        OCJP Encyclopedia Tutorials

Consider the following application:

1. class Q6 {
2. public static void main(String args[]){
3. Holder h = new Holder();
4. h.held = 100;
5. h.bump(h);
6. System.out.println(h.held);
7. }
8. }
9.
10. class Holder {
11. public int held;
12. public void bump(Holder theHolder){theHolder.held++;}
13. }
What value is printed out at line 6?

A. 0.
B. 1.
C. 100.
D. 101.
Answer:  D is correct. A holder is constructed on line 6. A reference to that holder is passed into method bump() on line 5. Within the method call, the holder's held variable is bumped from 100 to 101.


Question: Consider the following application:

1. class Q7 {
2. public static void main(String args[]){
3. double d = 12.3;
4. Decrementer dec = new Decrementer();
5. dec.decrement(d);
6. System.out.println(d);
7. }
8. }
9.
10. class Decrementer {
11. public void decrement(double decMe){decMe = decMe - 1.0;}
12. }
What value is printed out at line 6?
A. 0.0
B. -1.0
C. 12.3
D. 11.3
Answer:C is correct. The decrement() method is passed a copy of the argument d; the copy gets decremented, but the original is untouched.

Question: What does the following code fragment print out at line 10?


1. try{
2. FileOutputStream fos = new FileOutputStream("xx");
3. for (byte b=10; b<50; b++)
4. fos.write(b);
5. fos.close();
6. RandomAccessFile raf = new RandomAccessFile("xx","r");
7. raf.seek(10);
8. int i = raf.read();
9. raf.close();
10. System.out.println("i=" + i);
8. }
9. catch (IOException e) {}


A. The output is i = 30.


B. The output is i = 20.


C. The output is i = 10.


D. There is no output because the code throws an exception at line 1.


E. There is no output because the code throws an exception at line 6.


Answer:B is correct. All the code is perfectly legal, so no exceptions are thrown. The first byte in the file is 10, the next byte is 11, the next is 12 and so on. The byte at file position 10 is 20, so the output is i = 20.

Question: Which of the following signatures are valid for the main() method entry point of an application?


A. public static void main()

B. public static void main(String arg[])

C. public void main(String [] arg)

D. public static void main(String[] args)

E. public static int main(String [] arg)

Answer:B and D are both acceptable


Question: What is the range of values that can be assigned to a variable of type short?


A. It depends on the underlying hardware.


B. 0 through 216-1


C. 0 through 232-1


D. -21515 through 215-1


E. -231 through 231-1.


Answer:D is correct. The range for a 16-bit short is -215 through 215-1. This range is part of the Java specification, regardless of the underlying hardware.


Question: A file is created with the following Code:

1. FileOutputStream fos = new FileOutputStream("datafile");
2. DataOutputstream dos = new DataOutputstream(fos); 
3. for(int i=0; i<500; i++)
4. dos.writeInt(i);

You would like to write code to read back the data from this file. Which solutions listed below will work? (Choose none, some, or all).


A. Construct a FileInputStream, passing the name of the file. Onto the FileInputStream, chain a DataInputStream, and call its readInt() method.


B. Construct a FileReader, passing the name of the file. Call the file reader's readInt() method.


C. Construct a PipedInputStream, passing the name of the file. Call the piped input stream's readInt() method.


D. Construct a RandomAccessFile, passing the name of the file. Call the random access file's readInt() method.


E. Construct a FileReader, passing the name of the file. Onto the FileReader, chain a DataInputStream, and call its readInt() method.


Answer:  A and D are correct. Solution A chains a data input stream onto a file input stream. Solution D simply uses the RandomAccessFile class. B fails because the FileReader class has no readInt() method; readers and writers only handle text. Solution C fails because the PipedInputStream class has nothing to do with file I/O. (Piped inout and output streams are used in inter-thread communication). Solution E fails because you cannot chain a data input stream onto a file reader. Readers read chars, and input streams handle bytes.

Sunday, January 13, 2013

OCJP QUIZ QUESTIONS - 6



public class Yikes {
public static void go(Long n) {System.out.println("Long ");}
public static void go(Short n) {System.out.println("Short ");}
public static void go(int n) {System.out.println("int ");}
public static void main(String [] args) {
short y = 6;
long z = 7;
go(y);
go(z);
}
}
What is the result?

A. int Long
B. Short Long
C. Compilation fails.
D. An exception is thrown at run time.


Question 2:
Which two statements are true about has-a and is-a relationships? (Choose
two.)

A. Inheritance represents an is-a relationship.
B. Inheritance represents a has-a relationship.
C. Interfaces must be used when creating a has-a relationship.
D. Instance variables can be used when creating a has-a relationship.
Answer: A, D
13. Given:
1. class Convert {
2. public static void main(String[] args) {
3. Long xL = new Long(456L);
4. long x1 = Long.valueOf("123");
5. Long x2 = Long.valueOf("123");
6. long x3 = xL.longValue();
7. Long x4 = xL.longValue();
8. Long x5 = Long.parseLong("456");
9. long x6 = Long.parseLong("123");
10. }
11. }
Which will compile using Java 5, but will NOT compile using Java 1.4? (Choose all that apply.)
A. Line 4.
B. Line 5.
C. Line 6.
D. Line 7.
E. Line 8.
F. Line 9.
Answer:
-> A, D, and E are correct. Because of the methods’ return types, these method calls required
autoboxing to compile.
-> B, C, and F are incorrect based on the above.
Which about the three java.lang classes String, StringBuilder, and StringBuffer are true? (Choose all that apply.)
A. All three classes have a length() method.
B. Objects of type StringBuffer are thread-safe.
C. All three classes have overloaded append() methods.
D. The "+" is an overloaded operator for all three classes.
E. According to the API, StringBuffer will be faster than StringBuilder under most
implementations.
F. The value of an instance of any of these three types can be modified through various
methods in the API.

Answer:
-> A and B are correct.
-> C is incorrect because String does not have an "append" method. D is incorrect because only String objects can be operated on using the overloaded "+" operator. E is backwards, StringBuilder is typically faster because it's not thread-safe. F is incorrect because String objects are immutable. A String reference can be altered to refer to a different String object, but the objects themselves are immutable.


 A JavaBeans component has the following field:
11. private boolean enabled;
Which two pairs of method declarations follow the JavaBeans standard for accessing this field? (Choose two.)
A. public void setEnabled( boolean enabled )
public boolean getEnabled()
B. public void setEnabled( boolean enabled )
public void isEnabled()
C. public void setEnabled( boolean enabled )
public boolean isEnabled()
D. public boolean setEnabled( boolean enabled )
public boolean getEnabled()                         
Answer: A, C

Given classes defined in two different files:
1. package util;
2. public class BitUtils {
3. public static void process(byte[]) { /* more code here */ }
4. }
1. package app;
2. public class SomeApp {
3. public static void main(String[] args) {
4. byte[] bytes = new byte[256];
5. // insert code here
6. }
7. }
What is required at line 5 in class SomeApp to use the process method of BitUtils?
A. process(bytes);
B. BitUtils.process(bytes);
C. util.BitUtils.process(bytes);
D. SomeApp cannot use methods in BitUtils.
E. import util.BitUtils.*; process(bytes);
Answer: C

Given:
11. public abstract class Shape {
12. private int x;
13. private int y;
14. public abstract void draw();
15. public void setAnchor(int x, int y) {
16. this.x = x;
17. this.y = y;
18. }
19. }
Which two classes use the Shape class correctly? (Choose two.)
A. public class Circle implements Shape {
private int radius;
}
B. public abstract class Circle extends Shape {
private int radius;
}
C. public class Circle extends Shape {
private int radius;
public void draw();
}
D. public abstract class Circle implements Shape {
private int radius;
public void draw();
}
E. public class Circle extends Shape {
private int radius;
public void draw() {/* code here */}
F. public abstract class Circle implements Shape {
private int radius;
public void draw() { /* code here */ }
Answer: B, E

Given:
55. int [] x = {1, 2, 3, 4, 5};
56. int y[] = x;
57. System.out.println(y[2]);
Which statement is true?
A. Line 57 will print the value 2.
B. Line 57 will print the value 3.
C. Compilation will fail because of an error in line 55.
D. Compilation will fail because of an error in line 56.
Answer: B

Thursday, January 3, 2013

OCJP Tutorial Excercise - 5

Given:

11. abstract class Vehicle { public int speed() { return 0; }
12. class Car extends Vehicle { public int speed() { return 60; }
13. class RaceCar extends Car { public int speed() { return 150; } ...
21. RaceCar racer = new RaceCar();
22. Car car = new RaceCar();
23 Vehicle vehicle = new RaceCar();
24 System.out.println(racer.speed() + ", " + car.speed() + ", " + vehicle.
speed());
What is the result?




A. 0, 0, 0
B. 150, 60, 0
C. Compilation fails.
D. 150, 150, 150
E. An exception is thrown at runtime.

Answer: D
=========================================================================
Given:
5. class Building { }
6. public class Barn extends Building {
7. public static void main(String[] args) {
8. Building build1 = new Building();
9. Barn barn1 = new Barn();
10. Barn barn2 = (Barn) build1;
11. Object obj1 = (Object) build1;
12. String str1 = (String) build1;
13. Building build2 = (Building) barn1;
14. }
15. }


Which is true?
A. If line 10 is removed, the compilation succeeds.
B. If line 11 is removed, the compilation succeeds.
C. If line 12 is removed, the compilation succeeds.
D. If line 13 is removed, the compilation succeeds.
E. More than one line must be removed for compilation to succeed.

Answer: C
=========================================================================
Given:
21. class Money {
22. private String country = "Canada";
23. public String getC() { return country; }
24. }
25. class Yen extends Money {
26. public String getC() { return super.country; }
27. }
28. public class Euro extends Money {
29. public String getC(int x) { return super.getC(); }
30. public static void main(String[] args) {
31. System.out.print(new Yen().getC() + " " + new Euro().getC());
32. }
33. }
What is the result
?

A. Canada
B. null Canada
C. Canada null
D. Canada Canada
E. Compilation fails due to an error on line 26.
F. Compilation fails due to an error on line 29.

Answer: E

Explanation/Reference:

The field Money.country is not visible


========================================================================
Given a valid DateFormat object named df, and
16. Date d = new Date(0L);
17. String ds = "December 15, 2004";
18. //insert code here
What updates d's value with the date represented by ds?


A. 18. d = df.parse(ds);
B. 18. d = df.getDate(ds);
C. 18. try {
19. d = df.parse(ds);
20. } catch(ParseException e) { };
D. 18. try {
19. d = df.getDate(ds);
20. } catch(ParseException e) { };

Answer: C

========================================================================
Given:
11. double input = 314159.26;
12. NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
13. String b;
14. //insert code here
Which code, inserted at line 14, sets the value of b to 314.159,26?


A. b = nf.parse( input );
B. b = nf.format( input );
C. b = nf.equals( input );
D. b = nf.parseObject( input );

Answer: B
========================================================================


Saturday, December 29, 2012

OCJP Questions - 2


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

What is the result?

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


Answer: E

*********************************************************************************

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

Answer: D

*********************************************************************************


Given:
11. String test = "Test A. Test B. Test C.";
12. // insert code here
13. String[] result = test.split(regex);
Which regular expression, inserted at line 12, correctly splits test into "Test A", "Test B", and "Test
C"?

A. String regex = "";
B. String regex = " ";
C. String regex = ".*";
D. String regex = "\\s";
E. String regex = "\\.\\s*";
F. String regex = "\\w[ \.] +";


Answer: E


*********************************************************************************

Friday, December 21, 2012

OCJP EXercise- II

How do you create a new cookie?

Choice 1
    Assign values to the document.cookie property.
Choice 2
    Clone another cookie.
Choice 3
    Call newCookie().
Choice 4
    Reset the expiration date on an existing cookie.
Choice 5
    Call document.newCookie().



======================================================================

Which one of the following is not Javascript Math Objects Property



LOG10

PI

E

LN10

LOG10E


=====================================================================

What is the difference between WAR and EAR files?

Choice 1
    WAR is used to package JAR files; EAR is used to package JSP files.
Choice 2
    WAR is used to package resources for Web applications; EAR is used to package Web applications themselves.
Choice 3
    WAR is used in pre- J2EE 1.4 application servers; EAR is its equivalent from J2EE 1.4 going forward.
Choice 4
    WAR is used to package Web applications; EAR is used to package enterprise resources for those Web applications.
Choice 5
    WAR is used to package Web applications; EAR is used to package WAR files and JAR files with EJBs.// answer

OCJP Exercise - I



class Test

{

public static void main(String [ ] args)

{

if (args.length == 1) | (args[1].equals("debug"))

{

System.out.println(args[0]);

}

else

{

System.out.println("Release");

}

}

}
Explanation:
An interesting and important difference:
- in C++/BASH/etc. args[0] contains the name and the path to the program running the main() (in this case "Test")
- in Java args[0] is actually the first parameter to the program (in this case "debug").
So a run-time java.lang.Array_Index_Out_Of_Bounds_Exception is thrown for the code above.
The "|" and ";" operators are checking both their operands, unlike the short circuit operators "||" and ";;" which try to be shorter by checking their right operand ONLY in case the first was not enough to determine the result.
To correct the code replace:
- "|" with ";;"
- args[1] with args[0]
then the output will be "debug".
public static void main(String[] args) {

String entries[] = {"entry1","entry2"};

int count=0;

while (entries [count++]!=null){

System.out.println(count);

}

System.out.println(count);

}
Expalnation:
An ArrayIndexOutOfBoundsException would be thrown when count ==2
===================================================================================
public static void main(String[] args) {

int x = 5, y;

while (++x < 7) {

y = 2;

}

System.out.println(x + y);

}
Explanation:
Before using local variables we must initialize with default values.
------------------------------------------------------
public static void main(String[] args) {
int x = 5, y=0;
while (++x < 7) {
y = 2;
}
System.out.println(x + y);
}
o/p: 7 + 2 = 9;
--------------------------------------------------------
public static void main(String[] args) {
int x ;
System.out.println("Java Champ");
}
o/p: code compiles fine and print Java Champ
Which two are valid declarations within an interface definition? (Choose two)
A. void methoda();
B. public double methoda();
C. public final double methoda();
D. static void methoda(double d1);
E. protected void methoda(double d1);
Answer: A, B
Given:
11. Float f = new Float("12");
12. switch (f) {
13. case 12: System.out.printIn("Twelve");
14. case 0: System.out.printIn("Zero");
15. default: System.out.printIn("Default");
16. }
What is the result?
A. Zero
B. Twelve
C. Default
D. Twelve
Zero
Default
E. Compilation fails.
Answer: E
Given:
1. public class X {
2. public static void main(String [] args) {
3. try {
4. badMethod();
5. System.out.print("A");
6. }
7. catch (Exception ex) {
8. System.out.print("B");
9. }
10. finally {
11. System.out.print("C");
12. }
13. System.out.print("D");
14. }
15. public static void badMethod() {
16. throw new RuntimeException();
17. }
18. }
What is the result?
A. AB
B. BC
C. ABC
D. BCD
E. Compilation fails.
Answer: D
Given:
10. public Object m() {
11. Object o = new Float(3.14F);
12. Object [] oa = new Object[1];
13. oa[0] = o;
14. o = null;
15. oa[0] = null;
16. return 0;
17. }
When is the Float object, created in line 11, eligible for garbage collection?
A. Just after line 13.
B. Just after line 14.
C. Just after line 15.
D. Just after line 16 (that is, as the method returns).
Answer: B
interface TestA
{
            String toString();
}
public class InterfaceExamples {

            /**
             * @param args
             */
            public static void main(String[] args) {
                        // TODO Auto-generated method stub
                        System.out.println(new TestA()
                        {
                                    public String toString()
                                    {
                                                return "test";
                                               
                                    }
                                   
                        });

            }

}

o/p:: test.

public class RunnableTest {
            public static void main(String[] args) {
                        // TODO Auto-generated method stub
                       
                        Runnable r= new Runnable()
                        {

                                    @Override
                                    public void run() {
                                                // TODO Auto-generated method stub
                                               
                                                System.out.println("cat");
                                               
                                    }
                                   
                        };
                        Thread t= new Thread(r)
                        {
                                    public void run() {
                                                // TODO Auto-generated method stub
                                               
                                                System.out.println("Dog");
                                               
                                    }
                        };
                        t.start();
            }

}
 o/p:: DOG