Showing posts with label Java Dumps. Show all posts
Showing posts with label Java Dumps. Show all posts

March 05, 2015

What is the result When f.addFive() and System.out.println(f.a) is Called ?

Given:

31. class Foo {
32. public int a = 3;
33. public void addFive() { a += 5; System.out.print("f "); }
34. }
35. class Bar extends Foo {
36. public int a = 8;
37. public void addFive() { this.a += 5; System.out.print("b " ); }
38. }

Invoked with: Foo f = new Bar(); f.addFive(); System.out.println(f.a);

What is the result?


A. b 3
B. b 8
C. b 13
D. f 3
E. f 8
F. f 13
G. Compilation fails.
H. An exception is thrown at runtime.









Answer:A

Explanation :

At run-time JVM calls the overridden method (addFive) of the Class Bar which extends Foo.Since this.a + = 5 is written in Line 37,Bar Object's integer variable a = 8 is added with 5 and will have its result 13.Then b is printed .


after executing or printing b,we have now a tricky part where f.a is written withing System.out.prinln () method.Question arises - Which value of a is printed ? Is it a value of Bar Class or a value of Foo class.

Always at Run-time JVM calls only overridden method of subclass which is decided by the Type of Object(In the above case Bar is the type of Object).But whenever we call or invoke any other data member like class's variables,It is decided by Type of Reference variable  and not by type of Object.

In the above question f.a , f is of type Foo ,now compiler first checks whether class Foo has int a variable ? -- Yes ,if it has ,Then call that Foo class int a value .Therefore a value 3 is printed along with b. (b 3) - Option A.

Which Man class properly represents the relationship "Man has a best friend who is a Dog"?

Given :

A. class Man extends Dog { }
B. class Man implements Dog { }
C. class Man { private BestFriend dog; }
D. class Man { private Dog bestFriend; }
E. class Man { private Dog<bestFriend>; }
F. class Man { private BestFriend<dog>; }









Answer: D

Explanation:

If the Class has entity reference then it is called Aggregation.Aggregation is also known for "HAS - A" relationship.
In the above question we have "Man has a best friend " which represents container-ship or "HAS-A" relationship . Therefore bestFriend is one of the Member of Man .

"Who is a Dog".This part may confuses us ,but in the question it is very much clear in stating that best friend is of type Dog . So Datatype is Dog and variable name is bestFriend .


Since we have Dog bestFriend as a data member of Man ,therefore Man has to be a Class which has this data member which satisfies "HAS-A" relationship.

Option D.


What design flaw is most likely the cause of these new bugs?

Given :

A company that makes Computer Assisted Design (CAD) software has, within its application,some utility classes that are used to perform 3D rendering tasks. The company's chief scientist has just improved the performance of one of the utility classes' key rendering algorithms, and has assigned a programmer to replace the old algorithm with the new algorithm. When the programmer begins researching the utility classes, she is happy to discover that the algorithm to
be replaced exists in only one class. The programmer reviews that class's API, and replaces the old algorithm with the new algorithm, being careful that her changes adhere strictly to the class's API. Once testing has begun, the programmer discovers that other classes that use the class she changed are no longer working properly. 



A. Inheritance
B. Tight coupling
C. Low cohesion
D. High cohesion
E. Loose coupling
F. Object immutability








Answer: B


Explanation:

Definition of coupling:Degree to which one class knows about another class.


When we are having loose coupling and tight coupling ?

Suppose there are two Classes, Class A and Class B .If the Class A depends or relies only on those parts of Class B ,which is exposed using the interface of Class B .Such Scenario between the Classes is Called as loose coupling.


Suppose there are two Classes, Class A and Class B .If the Class A depends or relies on the parts of Class B ,which are not exposed through the interface of Class B .Such Scenario between the Classes is Called as Tight coupling.


In the above question the new Algorithm is asked to be implemented on Class's API and all other Classes which depends or relies on Class's API got affected due to Tight coupling.Option B.

March 02, 2015

What is the result when test("four") ,test("tee"),test("to") is Called ?

Given:

11. public static void test(String str) {
12. int check = 4;
13. if (check = str.length()) {
14. System.out.print(str.charAt(check -= 1) +", ");
15. } else {
16. System.out.print(str.charAt(0) + ", ");
17. }
18. } 
     \\ and the invocation:
21. test("four");
22. test("tee");
23. test("to");


A. r, t, t,
B. r, e, o,
C. Compilation fails.
D. An exception is thrown at runtime.








Answer: C

Explanation:

The biggest problem Java programmers confuse is with - if(condition) where to the condition they take it as  0 or 1 ( << its Wrong ,its not 0 or 1).In Java the Condition has to be either true or false (in words) and not 0 or 1.


Java has a separate data type called Boolean for condition  which evaluates to true or false (in words).But In Languages like C/C++ it is not so ,we use 1 to represent true and 0 to represent false.

Output of the above code is 
error: incompatible types
         if(check = str.length() ) {
                     ^
required :Boolean
found :    Int


The Entire trick in the above code is that they have used assignment operator = Instead of relational operator == .Therefore leads to Compilation failure .Option C





What is the result when you run the below Java program ?

Given:

13. public class Pass {
14. public static void main(String [] args) {
15. int x = 5;
16. Pass p = new Pass();
17. p.doStuff(x);
18. System.out.print(" main x = " + x);
19. }
20.
21. void doStuff(int x) {
22. System.out.print(" doStuff x = " + x++);
23. }
24. }




A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6 main x = 6
D. doStuff x = 5 main x = 5
E. doStuff x = 5 main x = 6
F. doStuff x = 6 main x = 5








Answer: D


Explanation:

This is a good example of how parameters are passed into the methods.Remember that always parameters are passed copy by value i.e changes in any value of the parameter in called method doesn't have affect in parameter in calling method.

Called method: doStuff()
Calling method : main method ( p.doStuff calls doStuff() method).

In the above example x is initialized with 5 and x is passed by copy by value to doStuff method .Here in the doStuff method we are post incrementing the value of x.But always SOP will print the value of x first then when ;(semicolon) is encountered the x gets incremented to 6 from 5.So doStuff x = 5 is printed.

Now the x in the main method will be 5 and not 6 because both methods x value have different memory locations and resources.  Option D.


What is the result when we try to Compile and Run ?

Given:

11. public class ItemTest {
12. private final int id;
13. public ItemTest(int id) { this.id = id; }
14. public void updateId(int newId) { id = newId; }
15. 
16. public static void main(String[] args) {
17. ItemTest fa = new ItemTest(42);
18. fa.updateId(69);
19. System.out.println(fa.id);
20. }
21. }




A. Compilation fails.
B. An exception is thrown at runtime.
C. The attribute id in the ItemTest object remains unchanged.
D. The attribute id in the ItemTest object is modified to the new value.
E. A new ItemTest object is created with the preferred value in the id attribute.









Answer: A


Explanation :

When you Compile and run the above program you get 

ItemTest.java:14:error: Cannot Assign value to final variable id 
 public void updateId(int newId) { id = newId; }
                                   ^
1 error .

Compilation fails because once we assign a value to final variable we can't change its value again .This is not because id is marked private or we haven't used this.id in updateId method .

Remember when you mark any variable as final ,Only once we can assign value to it and we can't change its value again.Burn that in.





When line 15 is reached, how many objects are eligible for the garbage collector?

Given:

3. interface Animal { void makeNoise(); }
4. class Horse implements Animal {
5. Long weight = 1200L;
6. public void makeNoise() { System.out.println("whinny"); }
7. }
8. public class Icelandic extends Horse {
9. public void makeNoise() { System.out.println("vinny"); }
10. public static void main(String[] args) {
11. Icelandic i1 = new Icelandic();
12. Icelandic i2 = new Icelandic();
13. Icelandic i3 = new Icelandic();
14. i3 = i1; i1 = i2; i2 = null; i3 = i1;
15. }
16. }



A. 0
B. 1
C. 2
D. 3
E. 4
F. 6









Answer:E

Explanation:

We use diagrammatic approach for your better understanding.Please read the question carefully before tracing the images below.

Initially when  three Icelandic are objects are created using reference variable i1,i2,i3   using the statements 
            Icelandic i1 = new Icelandic();
            Icelandic i2 = new Icelandic();
            Icelandic i3 = new Icelandic();

Remember Long weight is a primitive type of object which is within Icelandic object. i1 is pointing to Object Icelandic A with weight object of Long type .Therefore Totally 2 Objects for i1 .Similarly 2 Objects for i2 and 2 Objects for i3. And also remember that single reference variable can't point to 2 objects but here in this case Long Weight object is a primitive data member of Icelandic Object. 

After i3 = i1



After i1 = i2 



After i2 = NULL

Since i1 pointing to Icelandic B ,when we write i3 =i1  - i3 is made to point to Icelandic B .


After i3 = i1

Therefore Icelandic A along with its Long weight object and Icelandic C along with its Long weight Object is eligible for Garbage Collection .Total 4 Objects are eligible for Garbage Collection.Option E.

March 01, 2015

Which code should be inserted at line 1 of Demo.java to compile and run Demo to print "pizzapizza"?

Given:

1. // Class Repetition
2. package utils;
3. public class Repetition {
4. public static String twice(String s) { return s + s; }
5. } 

// and given another class Demo: 


1. // insert code here <<

2.
3. public class Demo {
4. public static void main(String[] args) {
5. System.out.println(twice("pizza"));
6. }
7. }





A. import utils.*;
B. static import utils.*;
C. import utils.Repetition.*;
D. static import utils.Repetition.*;
E. import utils.Repetition.twice();
F. import static utils.Repetition.twice;
G. static import utils.Repetition.twice;









Answer: F

Explanation:

Static import feature allows to access the static members of a class without the class qualification.The Correct Syntax of writing Static import is :import static fully qualified package name.

Twice method is present within Class Repetition and Class Repetition is present within utils Package So the fully qualified package will be utils.Repetition.twice.

When Twice method is called ,it will return PizzaPizza two concatenated String and will print PizzaPizza from the SOP.Therefore Option F is correct.

Which regular expression, inserted at line 12, correctly splits test into "Test A", "Test B", and "Test C"?

Given:

11. String test = "Test A. Test B. Test C.";
12. // insert code here
13. String[] result = test.split(regex);



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









Answer: E

Explanation:

Remember that if you need to create a String that contains a double quote " or a backslash \ you need to add an escape character first.If you need to search for periods (.) in your source data and If you just put a period in the regex expression, you get the "any character" behavior. 

So, what if you try \. ? Now the Java compiler thinks you're trying to create an escape sequence that doesn’t exist. 

The correct syntax to do so is 
String s = "ab.cde.fg";
String[] tokens = s.split("\\.");
which gives Output as :
abcdefg

Removes .(dot) and joins them.

Similarly \\s refers any occurrence of White Space and \\s* refers to occurrence of White Space character zero or more times .

String regex = "\\.\\s*"; is used which tells compiler that when both .(dot) and any number of White  Space occurs together then remove them .Therefore output will be Test ATest BTest C .



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

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. }



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

Explanation :

The java command-line argument is an argument i.e. passed while running the java program.The arguments passed from the console is a String type argument and can be received in the java program and it can be used as an input.

In the above example "12" is passed as a String when we run - java Converter 12 .Now we are storing String - 12 in integer i without using static method Integer.parseInt(str) which leads to Compile Time Error > 

line no:5: incompatible types
found : java.lang.String
required: java.lang.Integer
Integer i = args[0];

Solution to the above problem is ,we need to use  Integer.parseInt(arg[0]) and then Store it in Integer i .



Which three are valid on line 12 ?

Given :

(Choose three.)

11. public interface Status {
12. /* insert code here */ int MY_VALUE = 10;
13. } 




A. final
B. static
C. native
D. public
E. private
F. abstract
G. protected









Answer: A,B,D

Explanation :

An interface by default 100% abstract ,So  while declaring any method by default compiler implicitly adds abstract keyword in the method header and while declaring any variable or constant by default compiler implicitly adds public static final .

While declaring any constant the variable name must be All Capitals .In the above question MY_VALUE is marked as final and therefore once 10 is assigned to it we can't change or alter its value again.

Therefore public static final int MY_VALUE = 10; is a correct syntax for declaring Constant and public static final are the three correct options .




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

Given:

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



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");









Answer: E

Explanation:

public StringBuilder append(String s) :is used to append the Specified String with the given String. Here sb1 is a reference variable of type of StringBuilder which has 123 as String in it. 

Now we need to append 123 with abc so we call sb1.append("abc"); which gives the output 123abc and remember unlike normal String where operation on 2 strings forms new String which doesn't affect the original given String but in String Builder it does affect the original String when we are using append method, therefore 123abc is stored in sb1 itself .


Next we are declaring String s1 as 123 and concat with String abc which gives new String 123abc .Now in-order to change the contents of original String s1 we store new String 123abc in s1 by writing s1 = s1.concat("abc"); .


By SOP of sb1 and s1 seperated by blank space we get the output as 123abc 123abc.Option E.

What is Stored in y[2][1] and What is the Output of Below Code Snippet ?

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. }



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









Answer: E


Explanation:

In General we can declare int array as int[] x or int []x or int x[] all of them are equivalent and same for one dimensional array.For two dimensional array int [][] x or int []x[] or int x [][] all of them equivalent and same .



Here in the Line 3 we declaring an integer multi dimensional array named as x and initializes integer values 1,2,0,0 for 0th row , 3,4,5,0 for 1st row , 6,7,8,9 for 2nd row .


Next we are storing the reference variable x in the y , therefore integer reference variable x and y both point to same array with elements 1,2,0,0 for 0th row , 3,4,5,0 for 1st row , 6,7,8,9 for 2nd row .

Then we are accessing 2nd row first element - y[2][1] .Remember array index starts with 0 and not from 1.Output is :7 ,Option E.

February 27, 2015

Which two code Fragments correctly create and initialize a Static Array of int elements?

Given :

(Choose two.)

A. static final int[] a = { 100,200 };
B. Line 1:static final int[] a;
   Line 2:static { a=new int[2]; a[0]=100; a[1]=200; }
C. static final int[] a = new int[2]{ 100,200 };
D. Line 1:static final int[] a;
   Line 2:static void init() { a = new int[3]; a[0]=100; a[1]=200; }









Answer: A,B


Explanation :

In general we declare an Array in this form [Access Specifiers][optional modifiers] Datatype [] ref-var = {Initialization} or new Datatype[Size] for one Dimensional Array. 

For example :
public static String[] stringArray = new String[size];

OR

public static String[] stringArray = {"String1","String2","String3"};

Therefore Option A is correct with the Syntax.

Initialization blocks run when the class is first loaded (a static initialization block) or when an instance is created (an instance initialization block).

In Option B ,reference variable declaration and instance is created with initialization is divided 2 parts as shown in Line 1 and Line 2 in Option b .Since Static block can access Static data members and initialize the data values for integer array ,Option is Correct in Syntax.Option A,B.







What gets Printed when a.foo() & b.foo() Called ?

Given:

11. class Alpha {
12. public void foo() { System.out.print("Afoo "); }
13. }
14. public class Beta extends Alpha {
15. public void foo() { System.out.print("Bfoo "); }
16. public static void main(String[] args) {
17. Alpha a = new Beta();
18. Beta b = (Beta)a;
19. a.foo();
20. b.foo();
21. }
22. }


A. Afoo Afoo
B. Afoo Bfoo
C. Bfoo Afoo
D. Bfoo Bfoo
E. Compilation fails.
F. An exception is thrown at runtime.







Answer: D


Explanation :

Super class Alpha reference variable to pointing to subclass object beta .So due to Runtime Polymorphism or Dynamic method Dispatch the overridden method foo() of Beta Class Object is called and Not foo method Alpha Class Object.

Even reference variable 'a' is of Type Alpha ,the Overridden method foo of Beta Class is called and therefore Bfoo is Printed first.

Now the reference variable 'a' which is of type Alpha is downcasted to Beta type.Therefore Beta b variable is pointing to Beta Object ,Where Alpha a was pointing to and therefore Beta Object foo method is called which prints Bfoo Again.Option D

Output :Bfoo Bfoo With Warning :Possible Loss of Data By Downcasting.

Remember :Which method is called is decided at runtime by Type of Object and not on Reference variable.Also Compiler only checks whether a reference variable of a Class is having its method or not.

Which code, Inserted at line 16, Correctly retrieves a local instance of a Point object?

Given:

10. class Line {
11. public class Point { public int x,y;}
12. public Point getPoint() { return new Point(); }
13. }
14. class Triangle {
15. public Triangle() {
16. // insert code here
17. }
18. }




A. Point p = Line.getPoint();
B. Line.Point p = Line.getPoint();
C. Point p = (new Line()).getPoint();
D. Line.Point p = (new Line()).getPoint();







Answer: D

Explanation :

getPoint() method is declared inside Line Class and outside Point class.So in-order to call getPoint() method we must first instantiate Line Class object . Therefore (new Line()).getPoint(); .

The reference variable of inner Point class must be declared in the form OuterClass.InnerClass ,ie Line.Point p ,Since we instantiate inner class Point object in Triangle class constructor .

Output is x and y integer variables of Point object is initialized with Zero and Point Object reference is returned to Triangle Constructor .And the correct Syntax to do so is Option D .


Here are the some other ways to Instantiate Inner class objects outside Outer Class :

new MyOuter().new MyInner(); or outerObjRef.new MyInner();



What is the Result of the Below Code Snippet ?

Given:

5. class Atom {
6. Atom() { System.out.print("atom "); }
7. }
8. class Rock extends Atom {
9. Rock(String type) { System.out.print(type); }
10. }
11. public class Mountain extends Rock {
12. Mountain() {
13. super("granite ");
14. new Rock("granite ");
15. }
16. public static void main(String[] a) { new Mountain(); }
17. }


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







Answer: F


Explanation :

Inside Main Method new Mountain object is created which calls its constructor in Line 12.Inside Mountain constructor ,super("granite") calls the Rocks constructor by passing granite String argument.Inside Rock constructor ,implicitly calls super() Atom constructor passing no argument.

Therefore atom is printed first from the SOP of Atom Constructor,then comes down to Rock constructor and prints whats is stored in rocks constructor's variable (String Type) which is Granite .

Comes down and now a new Rock object gets created by calling constructor of Rock passing "granite" String argument and gets accepted in String type= "granite".Inside Rock constructor ,implicitly calls ( super() ) Atom constructor passing no argument.


Therefore atom is printed again ,then comes down to Rock constructor and prints whats is stored in type a String variable which is Granite.

Comes down to mountain method and comes back to main method and program terminates printing the result Atom Granite Atom Granite .option F.