Compilation and output of the digits “1”, “2” and “3”, but the order can’t be determined

Compilation and output of onetwothree

Compilation but runtime error at line 10

2 . The following is part of the code for an application that will run two time consuming processes in two Threads. We want to be sure that all threads get a chance to run.Which statement at line 9 will accomplish this?

A compiler error in line 3 due to the lack of a constructor for DerivedSample

4 . You have a working class ClassA that has a method declared as follows:

protected float calculate( int x, int y )

Now you have to extend ClassA with ClassB and override the calculate method with a new version. This new calculate will have to call the processB() method which has the following declaration, where MyException is a custom Exception extending Exception.

5 . The general contract for the hashCode method states that under certain conditions, the hashCode method for a given object must always produce the same int value as long as data that affects operation of the equals method remains the same?

Choose the one below:

During the execution of a single program

Every execution of the program on a given machine

Every execution of the program using a given SDK version

Every execution of the program on any SDK version from 1.4.0 on

6 . The following code fragments show various uses of the key word synchronized. Which of them could be used to protect a resource against modification by multiple Threads at the same time?

public synchronized class BankAccount { // methods and variables to be protected }

If we put the following statement after the loop, it would report “j = 5″ System.out.println( “j = ” + j );

17 . Which of the following statements are true?

The TreeMap class implements the Collection interface

The Vector class allows elements to be accessed using the get(int offset) method

The TreeSet class stores values in sorted order and ensures that the values are unique

The elements in the LinkedHashMap are kept in sorted order

18 . The GenericFruit class declares the following method to return a float number of calories in the average serving size?

public float aveCalories( )

Your Apple class, which extends GenericFruit, overrides this method.In a DietSelection class which extends Object, you want to use the GenericFruit method on an Apple object instead of the method in the Apple class.

Select the correct way to finish the statement in the following code fragment so that the GenericFruit version of aveCalories is called using the gf reference.

20 . You have a class, MyThing, that implements a finalize method. You have a method which creates a MyThing array and fills it with MyThing objects. When all of the contents of the array become eligible for garbage collection, which of the following statements about the process of garbage collection are true?

The first MyThing created, as the oldest, will be collected first

The last MyThing created, as the youngest, will be collected first

Java does not guarantee the order of collection

The finalize method of each MyThing will be run as soon as the garbage collection mechanism determines it is unreachable

49 . The greek letter Pi in the Unicode used by Java has the value 3c0 in hexadecimal representation.Write the Unicode literal which would be used to initialize a char variable to Pi. Just write the Unicode literal char, not the complete expression. In other words, what should replace XXXX in the following statement?

char PiChar = XXXX;

50 . The following method definition is designed to parse and return an integer from an input string which is expected to look like “nnn, ParameterName”. In the event of a NumberFormatException, the method is to return -1?

What happens when we try to compile this code and execute the method with an input string which does not contain a comma (,) separating the number from the text data?

Compilation error @line 6

Prints the error message to standard output and returns -1

A NullPointerException is thrown @line 3

A StringIndexOutOfBoundsException is thrown @line 3

Answers

1 : 1 is correct. Explanation: (1)(2) & (3) The compiler realizes that the get returns an Object reference which needs a cast to type Integer. (4) Even if the cast was supplied to fix the compile error, the outputwould be the integer values, not the keys. (5) The need for a cast is found by the compiler so E does not occur.

2 : 1 & 4 is correct. Explanation: (1) This works because yield is a static method of the Thread class, although the currentThread call is not necessary (2) You can’t use sleep without providing for anInterruptedException (3) This does not work because the TestQ20 class does not extend Thread (4) This works because yield is a static method of the Thread class.(Credit: LanWrights)

3 : 2 is correct. Explanation: (1) No, the compiler uses paramA in the TechnoSample class, not DerivedSample (2) The address of paramA is fixed at compile time based on the TechnoSample reference type so thevalue found is 9 (3) No, this cast is perfectly legal and essential to get the code to compile (4) No, the compiler provides a default constructor. (Credit: LanWrights)

4 : 1 is correct. Explanation: (1) Handling the exception internally is the only option that works (2) The compiler won’t let you use an overriding method that declares a checked exception when the original methoddoes not (3) This does not solve anything. In addition to the exception problem, you can’t declare an overriding method that is more private than the original (4) You can’t changethe exception type by the throws declaration, the compiler will reject this. (Credit: LanWrights)

5 : 1 is correct. Explanation: The contract only requires that the same value be returned during one execution. Thus a hashcode should never be assumed to be the same between executions.

6 : 2 & 4 is correct. Explanation: (1) Wrong because you can’t label a class as synchronized (2) This would work by locking the object during the entire adjustBalance method (3) Wrong for several reasons, 1. youcan’t synchronize on a primitive, and 2. f is a local variable (4)This would work by using the separate “lock” Object as a synchronization flag during execution of thesynchronized code block. (Credit: LanWrights)

7 : 2 is correct. Explanation: (1) No, a call to a method that throws an exception may itself be in a method that throws that exception or if the Exception is a descendent of RuntimException it need notcatch the exception at all (2) Yes, as with other types of code blocks, a variable created in a try or catch block is local to that block (3) No, a try statement may be matchedwith a finally statement without a catch block (4) A finally block may contain its own try/catch statement and it is common in Java programming to put in such a construct.

8 : 1 & 2 is correct. Explanation: (1) The strictfp modifier can be applied to an entire class. It forces all floating-point operations in the class to adhere to the strict standard (2) When applied to a method,all floating point expressions in the method will use the strict standard (3) No, strictfp can only be used with an entire class, an interface or a method (4) No, strictfp canonly be used with an entire class, an interface or a method.

9 : 1 & 4 is correct. Explanation: (1) Yes, this statement is incorrect, inner classes are forbidden to have the same name as the enclosing class (4) Yes, this statement is incorrect, anonymous inner classes mayextend a variety of classes. (2) & (3) are not correct.

10 : 1,2 & 5 is correct. Explanation: (1) Certainly, any reference can be cast to Object(2) Yes, any reference can be cast to a superclass, the fact that BaseWidget is abstract does not alter this (3) No, SlowWidgetcan’t be cast to Runnable, only FastWidget could (4) No, FastWidget is not a superclass of SlowWidget (5) Certainly.

11 : 1 & 2 is correct. Explanation: (1) This works because Nested is a static member of TopLevel so it does not need an instance. However, outside the TopLevel class you would need the form shown in b (2) Thisworks because the full name of Nested is TopLevel.Nested – you could use this form outside the TopLevel class (3) This is an incorrect constructor, as a static member of TopLevel,Nested does not need an instance (4) This is an incorrect constructor, as a static member of TopLevel, Nested does not need an instance.

12 : 2 & 3 is correct. Explanation: (1) incorrect because the System.out.print method has a return type of void which is not allowed after the : of an assert statement (2) a valid assert statement (3) a validassert statement (4) incorrect because the assert statement must check that something is true, and the code given performs an assignment returning an int primitive.

13 : 2 & 4 is correct. Explanation: (1) No, this refers to a member of the inner class (2) Yes, although needlessly convoluted, NormClass.this refers to the enclosing object (3) No, this is backwards (4) Yes, thesimplest way since the inner class can access all instance members directly.

14 : 5 is correct. Explanation: (1) No, HashMap has the put(key, object) method required by the Map interface (2) There is no error, Map does not care about duplicate elements (3) No, the Iterator accesses thekeys, which are “1”, “2” and “3” (4) Although these are the key Strings, the order is not guaranteed (5) Yes, the HashMap class stores elements as key/value pairs but the order ofkeys is not guaranteed.

16 : 2 is correct. Explanation: (1) No, this is not the correct form, see (2). (2) Right, this is not a correct initializer because it combines declaring and setting the variable j which is already definedin the method (3) Even if the loop initializer was fixed, the variable i is out of scope and can’t be used (4) The program can’t compile and run as shown.

17 : 2 & 3 is correct. Explanation: (1) No, TreeMap implements the Map interface (2) Yes, Vector has the get( index ) method as required by the List interface (3) Yes, TreeSet implements the SortedSet interface, whichensures that the values are unique and store in the “natural order” of the elements (4) The elements in the LinkedHashMap are held in order of addition, not sorted.

18 : 4 is correct. Explanation: (1) wrong because the runtime resolution of method calls finds the Apple method (2) wrong because this extra cast does not change the object type (3) does not create a valid Javastatement (4) correct, there is no way for a class outside the GenericFruit hierarchy to call the GenericFruit method using an Apple reference.

19 : 1 is correct. Explanation: (1) Catch statments must proceed from most specific to most general, thus Exception must always be the last exception type caught. (2) See (1), but note that if the catch orderwas fixed, the finally clause would be executed and 2 returned. (3) See (1) & (2). (4) No, of course not (5) No, this syntax is fine.

20 : 3 is correct. Explanation: (1) & (2) see (3). (3) The Java Language Specification does not guarantee anything about the order in which objects are collected (4) Running the finalize method can be separatefrom the mechanism that determines an object is unreachable so the order can’t be guaranteed.

21 : 3 is correct. Explanation: (1) Even if this was the wrong signature, it would not prevent compilation. (2) This is the correct signature for the finalize method so it will run when objects are garbagecollected. (3) Only 2 finalizations will occur since obj still holds a reference. (4) See (3).

22 : 2 & 3 is correct. Explanation: (1) No, see (2). (2) Yes, the Math class has the max and min methods for integer and floating point primitives. (3) Yes, the String parsing methods are in the primitive wrapperclasses. (4) No, see (3).

23 : 1 is correct. Explanation: The line after the break statement would always be unreachable and thus the code would not compile.

24 : 3 is correct. Explanation: (1) The compiler does not object because the static final variable still points to the same object. Only if we had tried to assign another StringBuffer to the variable wouldthe compiler object. (2) & (4) see (3). (3) Yes, that is the contents of the variable after modification.

25 : 3 is correct. Explanation: (1) No, any array can be cast to an Object reference (2) No, because Object is the parent class of String, this is legal (3) This assignment causes an error because the type of aprimitive array can’t be changed to another primitive type by a cast (4) No, any array can be cast to an Object reference.

26 : 1,3 & 5 is correct. Explanation: The Set interface does not permit duplicate elements, but since ArrayList implements List and not Set, it can hold duplicates. Its methods are not synchronized, so it’s notthread-safe on its own. List classes use a ListIterator rather than a simple Iterator, because a ListIterator lets you traverse bi-directionally.It is well-suited for fast random access, and implements the RandomAccess interface. It also implements java.util.Collection (not Collections with an ‘s’).

27 : 2 is correct. Explanation: Math.abs returns the absolute of a number. Math.ceil returns the smallest double that is greater than or equal to the number, and also rounds it to the nearest integer.Math.floor returns the largest double that is less than or equal to the number, and rounds it to the nearest integer. Math.round returns the integer that is closest to the number,by adding .5 to the number and then truncating to get the nearest integer. Option “A” would be the correct answer if the System.out.println() statement had not includedthe “”, since that would cause the integer variables to be arithmetically added rather than concatenated as String values. (courtesy: Sun Microsystems)

29 : 6 is correct. Explanation: Option 6 is the correct answer. You can request that an object be destroyed, but only the GC decides when is actually destroyed. (courtesy: Sun Microsystems)

30 : 5 is correct. Explanation: Option 5 is the correct answer. The instance variable b is initialized to false, reset to false on line 8 and falls through to line 15, where x is set to 4.(courtesy: Sun Microsystems)

31 : 7 is correct. Explanation: Objects become eligible for garbage collection when all references to the object are removed from active threads. With the exception of a WeakHashMap a key stored in a Map isnot garbage collected when the references to the key are removed. A WeakHashMap can be used to avoid the memory leaks generally associate with the use of other implementations ofthe Map interface. (credit: danchisholm)

32 : 2 is correct. Explanation: Thread a1 intends to wait forever since no other thread invokes the notify method. After starting thread a1 the main method invokes the interrupt method on thread a1. Inresponse, thread a1 moves out of the Not-Runnable state. Once the thread begins to run it throws an InterruptedException and clears the interrupted flag. The exception is caught andthe interrupted method is invoked to test the state of the interrupted flag. Since the flag was cleared when the exception was thrown the return value of the interruptedmethod is false. (credit: danchisholm)

33 : 6 is correct. Explanation: Boolean class contains 2 instances of Boolean objs that are declared public static final Boolean.The 1st is Boolean.FALSE & wraps the primitive bool value false.The other is Boolean.TRUE and wraps the primitive boolean value true. Theequality operator ‘ll return true if the left & right operand are both Boolean.TRUE or if the left & right operand are both Boolean.FALSE. The same is true if the results of the Boolean.valueOf method are compared with the equality operator’cause the comparison is just a comparison of references to the constants Boolean.TRUE or Boolean.FALSE. Please note that Boolean.valueOf is generally preferable over the use of the Boolean constructor ’cause the Boolean.valueOf method does notcreate a new instance of a Boolean obj. The valueOf method is much faster than the use of the constructor & also saves memory. The use of the Boolean constructor is not recommended in any situation where the valueOf method is applicable.

34 : 4 is correct. Explanation: An anonymous class can extend another class or implement an interface. If the anonymous class extends another class then the class instance creation expression can include parameters. The parameters will be passed to a constructor ofthe super class. If the anonymous class implements an interface, then the instance creation expression can not include any parameters. An anonymous class can not be extended so it also can not be abstract. An anonymous classcan not be static. An anonymous class can not declare a constructor, but it can declare an instance initializer. (Credit: danchisholm)

35 : 2 is correct. Explanation: Though TechnoSuper is an abstract class, a TechnoSuper variable could correctly be initialized with a reference to any subclass of TechnoSuper that is not abstract. HereTechnoSub is not abstract and the statement (2) would be legal.

36 : 1 is correct. Explanation: This code implements an anonymous inner class that implements the Remote interface and will compile without error. Option 2 should be obvious nonsense as you cannot directly instantiate an interface (credit: www.examulator.com)

37 : 4 is correct. Explanation: The ~ operator flips all of the bits including the sign bit. Thus in this case you start off with 4 which in binary is 0000 0000 0000 0000 0000 0000 0000 0100 and after the ~ operation you end up with 1111 1111 1111 1111 1111 1111 1111 1011, which is binary representation of decima -5.Please read 2’s complement number encoding for negative value representation in Java.

38 : 2 is correct. Explanation: This code will produce a java.lang.IllegalMonitorStateException at runtime because the wait/notify code is not within synchronized code.(Credit: www.examulator.com)

40 : 3 is correct. Explanation: It permits null values and null keys. It stores information as key/value pairs.This class does not guarantee the order of its elements over time.

41 : 1,3 & 4 is correct. Explanation: An interface can extend another interface but not a class. Interface methods are abstract by default. The purpose of interface methods are that they should be implemented in other classes, so there would not be much point in them beingfinal. (Credit: www.examulator.com)

42 : 2 is correct. Explanation: Having the same hashCode does not tell you that two objects are equal. If they are equal they must return the same HashCode value, but if they are not equal they could returnthe same hashCode value.

43 : 1 & 4 is correct. Explanation: An overriden method must have the same parameter types as in the parent class, but it does not need to have the same names for those parameters. An overriden method cannot throw exceptions not declared in the parent class version, but itcan throw fewer or no exceptions.

44 : 4 is correct. Explanation: If that seems a vauge answer it is because you cannot be certain of the system that the underlying OS uses for allocating cycles for a Thread. The chances are that once the thread has been spun off in the call to start in the methodpiggy the main method will run to completion and the value of sName will still be vandeluer before the Thread modifies it. You cannot be certain of this though.

Just because sName is static does not mean that passing it to a method gives the method the original copy. The method only sees a locally created copy and any changes to it will not be reflected on return to the calling method.

45 : 2 is correct. Explanation: (1) Fails to compile. As far as the compiler is concerned, obj is a plain Object so it objects to the assignment to a Runnable reference. (2) Compiles and runs. The compilerassumes you know what you are doing with the cast to Runnable. (3) Compiles but fails to run. Because of the specific cast, the compiler thinks you know what you are doing, but thetype of the base reference is checked when the statement executes and a ClassCastException is thrown. (4) Fails to compile. see (1). (Credit: www.lanw.com)

46 : 2 is correct. Explanation: (1) No – I is not a Long object, so the test fails. (2) Correct – the test results in a false value because I is not a Long object. All of the primitive wrapper object “equals”tests only compare content once they have determined that the input object is of the correct class. (3) & (4) No – because the signature of the equals method will take any object. (Credit: www.lanw.com)

47 : 2 is correct. Explanation: (1) No – the compiler will object because the public class name does not match the file name. (2) Right – the compiler error message is “public class Base must be defined in a filecalled Base.java”. Although it is common for a single Java source file to generate more than one class file on compilation, two public classes cannot occupy the same Java source file.(3) No – but if the source file had been named Base.java, then option (3) would be correct. (Credit: www.lanw.com)

48 : 1,2,3 & 4 is correct. Explanation: All of these changes would eliminate the warning. Both (1) & (2) provide for initializing the reference. (3) ensured that tmp gets initialized no matter what the value of n.(4) makes tmp a member variable which will be initialized to null.(Credit: www.lanw.com)

49 : \u03c0. Explanation: \u03c0 Or \u03C0. Unicode literals always starts with “\u” and have four hexadecimal digits. The hexadecimal digits can be either upper or lower case. (Credit: www.lanw.com)

50 : 1 is correct. Explanation: The scope of the “tmp” String is confined to the try block. (Credit: www.lanw.com)

Comments

comments

Related posts:

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

About Us

Javabeat.net is a blog dedicated to Java/J2EE developers. This site focus on beginners and advanced developers. We constantly write fresh content on J2EE topics like Spring, Hibernate and wide variety of J2EE frameworks.