Edzy_Java

  BlogJava :: 首页 ::  ::  ::  :: 管理 ::
  58 随笔 :: 12 文章 :: 11 评论 :: 0 Trackbacks

Answers (1)
________________________________________
Answer 1)

5) int i=10;

explanation:

1) float f=1.3;

Will not compile because the default type of a number with a floating point component is a double. This would compile with a cast as in

float f=(float) 1.3

2) char c="a";

Will not compile because a char (16 bit unsigned integer) must be defined with single quotes. This would compile if it were in the form

char c='a';

3) byte b=257;

Will not compile because a byte is eight bits. Take of one bit for the sign component you can define numbers between

-128 to +127

4) a boolean value can either be true or false, null is not allowed
________________________________________

Answer 2)

1) Can't make static reference to void amethod.

Because main is defined as static you need to create an instance of the class in order to call any non-static methods. Thus a typical way to do this would be.

MyClass m=new MyClass();

m.amethod();

Answer 2 is an attempt to confuse because the convention is for a main method to be in the form

String argv[]

That argv is just a convention and any acceptable identifier for a string array can be used. Answers 3 and 4 are just nonsense.
________________________________________

Answer 3)

2 and 3 will compile without error.

1 will not compile because any package declaration must come before any other code. Comments may appear anywhere
________________________________________

Answer 4)

1) A byte is a signed 8 bit integer.

________________________________________

Answer 5)

4) Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2"

Unlike C/C++ java does not start the parameter count with the program name. It does however start from zero. So in this case zero starts with good, morning would be 1 and there is no parameter 2 so an exception is raised.
________________________________________

Answer 6)

1) if

3) goto

4) while

5) case

then is not a Java keyword, though if you are from a VB background you might think it was. Goto is a reserved word in Java.
________________________________________

Answer 7)

2) variable2

3) _whatavariable

4) _3_

5) $anothervar

An identifier can begin with a letter (most common) or a dollar sign($) or an underscore(_). An identifier cannot start with anything else such as a number, a hash, # or a dash -. An identifier cannot have a dash in its body, but it may have an underscore _. Choice 4) _3_ looks strange but it is an acceptable, if unwise form for an identifier.
________________________________________

Answer 8)

4) 0

Class level variables are always initialised to default values. In the case of an int this will be 0. Method level variables are not given default values and if you attempt to use one before it has been initialised it will cause the

Error Variable i may not have been initialized

type of error.
________________________________________

Answer 9)

3 ) 2

No error will be triggered.

Like in C/C++, arrays are always referenced from 0. Java allows an array to be populated at creation time. The size of array is taken from the number of initializers. If you put a size within any of the square brackets you will get an error.
________________________________________

Answer 10)

3) 0

Arrays are always initialised when they are created. As this is an array of ints it will be initalised with zeros.
________________________________________

Answer 11)

3) Error Mine must be declared abstract

A class that contains an abstract method must itself be declared as abstract. It may however contain non abstract methods. Any class derived from an abstract class must either define all of the abstract methods or be declared abstract itself.
________________________________________

Answer 12)

3) one, two, default
Code will continue to fall through a case statement until it encounters a break.
________________________________________

Answer 13)

2) default, zero

Although it is normally placed last the default statement does not have to be the last item as you fall through the case block. Because there is no case label found matching the expression the default label is executed and the code continues to fall through until it encounters a break.
________________________________________

Answer 14)

2,3

Example 1 will not compile because if must always test a boolean. This can catch out C/C++ programmers who expect the test to be for either 0 or not 0.
________________________________________

Answer 15)

3) No such file found, doing finally, -1

The no such file found message is to be expected, however you can get caught out if you are not aware that the finally clause is almost always executed, even if there is a return statement.
________________________________________

Answer 16)

1) Methods cannot be overriden to be more private

Static methods cannot be overriden but they can be overloaded. If you have doubts about that statement, please follow and read carefully the link given to the Sun tutorial below. There is no logic or reason why private methods should not be overloaded. Option 4 is a jumbled up version of the limitations of exceptions for overriden methods
________________________________________

Answer 17)

3) Runtime Exception

Without the cast to sub you would get a compile time error. The cast tells the compiler that you really mean to do this and the actual type of b does not get resolved until runtime. Casting down the object hierarchy is a problem, as the compiler cannot be sure what has been implemented in descendent classes. Casting up is not a problem because sub classes will have the features of the base classes. This can feel counter intuitive if you are aware that with primitives casting is allowed for widening operations (ie byte to int).
________________________________________

Answer 18)

1) System.out.println( -1 >>> 2);will output a result larger than 10

2) System.out.println( -1 >>> 2); will output a positive number

3) System.out.println( 2 >> 1); will output the number 1

You can test this with the following class

public class shift{

static int i=2;

public static void main(String argv[]){

        System.out.println( -1  >>> 2);

        System.out.println( -1  >>> 2);

        System.out.println( 2  >> 1);

        }

}

Java does not have a <<< operator. The operation 1 << 2 would output 4

Because of the way twos complement number representation works the unsigned right shift operation means a small shift in a negative number can return a very large value so the output of option 1 will be much larger than 10.

The unsigned right shift places no significance on the leading bit that indicates the sign. For this shift the value 1 of the bit sign is replaced with a zero turning the result into a positive number for option 2.
________________________________________

Answer 19)

4) Compilation and output of either "vandaleur", "vandaleur 0", "vandaleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"

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 method piggy 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.
________________________________________

Answer 20)

3) One button occupying the entire frame saying Bye

The default layout manager for a Frame is a border layout. If directions are not given (ie North, South, East or West), any button will simply go in the centre and occupy all the space. An additional button will simply be placed over the previous button. What you would probably want in a real example is to set up a flow layout as in

setLayout(new FlowLayout());

Which would allow the buttons to both appear side by side, given the appropriate font and size.

Applets and panels have a default FlowLayout manager
________________________________________

Answer 21)

1,2

Value for i=1 Value for j=1

Value for i=2 Value for j=1

The statement continue outer causes the code to jump to the label outer and the for loop increments to the next number.
________________________________________

Answer 22)

4) Runtime error, an exception will be thrown

A call to

wait/notify must be within synchronized code. With JDK1.2 this code throws the error message

java.lang.IllegalMonitorStateException: current thread not owner

        at java.lang.Object.wait(Native Method)

        at java.lang.Object.wait(Object.java:424)

        at DSRoss.notwait(Compiled Code)

        at DSRoss.run(Agg.java:21)
________________________________________

Answer 23)

2,3

Options 1, & 4 will not compile as they attempt to throw Exceptions not declared in the base class. Because options 2 and 3 take a parameter of type long they represent overloading not overriding and there is no such limitations on overloaded methods.
________________________________________

Answer 24)

3) System.out.println(Math.ceil(-4.7));

Options 1 and 2 will produce -5 and option 4 will not compile because the min method requires 2 parameters.
________________________________________

Answer 25)

3) Compile time error

The wrapper classes cannot be used like primitives.

Depending on your compiler you will get an error that says someting like "Error: Can't convert java lang Integer". Wrapper classes have similar names to primitives but all start with upper case letters.
Thus in this case we have int as a primitive and Integer as a wrapper. The objectives do not specifically mention the wrapper classes but don't be surprised if they come up.
________________________________________

Answer 26)

2) ic

This is a bit of a catch question. Anyone with a C/C++ background would figure out that addressing in strings starts with 0 so that 1 corresponds to i in the string Bicycle. The catch is that the second parameter returns the endcharacter minus 1. In this case it means instead of the "icy" being returned as intuition would expect it is only "ic".
________________________________________

Answer 27)

3) s.indexOf('v');

charAt returns the letter at the position rather than searching for a letter and returning the position, MID is just to confuse the Basic Programmers, indexOf(s,'v'); is how some future VB/J++ nightmare hybrid, might perform such a calculation.
________________________________________

Answer 28)

1) s3=s1 + s2;

Java does not allow operator overloading as in C++, but for the sake of convenience the + operator is overridden for strings.
________________________________________

Answer 29)

4) 7

The | is known as the Or operator, you could think of it as the either/or operator. Turning the numbers into binary gives

4=100

3=011

For each position, if either number contains a 1 the result will contain a result in that position. As every position contains a 1 the result will be
111

Which is decimal 7.
________________________________________

Answer 30)

1,2,3

public, private, static are all legal access modifiers for this inner class.
________________________________________

Answer 31)

3) Output of first0, first1, second0, second1

Note that this code overrides and calls the start method. If you wished to get the output mixed you would need to override the run method but call the start method.
________________________________________

Answer 32) 

2) setLayout(new GridLayout(2,2));

Changing the layout manager is the same for an Applet or an application. Answer 1 is wrong though it might have been a reasonable name for the designers to choose. Answers 3 and 4 are incorrect because changing the layout manager always requires an instance of one of the Layout Managers and these are bogus methods.

Instead of creating the anonymous instance of the Layout manager as in option 2 you can also create a named instance and pass that as a parameter. This is often what automatic code generators such as Borland/Inprise JBuilder do.
________________________________________

Answer 33)

3) The code will cause an error at compile time

The error is caused because run should have a void not an int return type.
Method redefined with different return type: int run() was defined as void run();
________________________________________

Answer 34)

3) Compilation and output of 0 followed by 1

The creation of an anonymous class as a parameter to go is fairly strange as you would expect it to override a method in its parent class (Turing). You don't have to though. The fact that class Turing extends Thread means the anonymous instance that is passed to go has a start method which then calls the run method.
________________________________________

Answer 35)

4) Compile time error

The only operator overloading offered by java is the + sign for the String class. A char is a 16 bit integer and cannot be concatenated to a string with the + operator.
________________________________________

Answer 36)

3) if(s.equalsIgnoreCase(s2))

String comparison is case sensitive so using the equals string method will not return a match. Using the==operator just compares where memory address of the references and noCaseMatch was just something I made up to give me a fourth slightly plausible option.
________________________________________

Answer 37)

1) s.setBackground(Color.pink);

For speakers of the more British spelt English note that there is no letter u in Color. Also the constants for colors are in lower case.
________________________________________

Answer 38)

4) The File class does not support directly changing the current directory.

This seems rather surprising to me, as changing the current directory is a very common requirement. You may be able to get around this limitation by creating a new instance of the File class passing the new directory to the constructor as the path name.
________________________________________

Answer 39)

1)With a fixed font you will see 5 characters, with a  proportional it will depend on the width of the characters

With a proportional font the letter w will occupy more space than the letter i. So if you have all wide characters you may have to scroll to the right to see the entire text of a TextField.
________________________________________

Answer 40)

3) On the line After //Two put super(10);

Constructors can only be invoked from within constructors.
________________________________________

Answer 41)

3) 10 and 40

when a parameter is passed to a method the method receives a copy of the value. The method can modify its value without affecting the original copy. Thus in this example when the value is printed out the method has not changed the value.
________________________________________

Answer 42)

4) for(int i=0; i< ia.length;i++)
________________________________________

Answer 43)

1) Error at compile time
________________________________________

Answer 44)

3)10

The name of the class might give you a clue with this question, Oct for Octal. Prefixing a number with a zero indicates that it is in Octal format. Thus when printed out it gets converted to base ten. 012 in octal means the first column from the right has a value of 2 and the next along has a value of one times eight. In decimal that adds up to 10.
________________________________________

Answer 45)

1) Error at compile time

The variable i is created at the level of amethod and will not be available inside the method multi.
________________________________________

Answer 46)

1) Set

The Set interface ensures that its elements are unique, but does not order the elements. In reality you probably wouldn't create your own class using the Set interface. You would be more likely to use one of the JDK classes that use the Set interface such as HashSet or TreeSet.
________________________________________

Answer 47)

4) Vector v=new Vector(100);

v.addElement("99")

A vector can only store objects not primitives. The parameter "99" for the addElement method pases a string object to the Vector. Option 1) creates a vector OK but then uses array syntax to attempt to assign a primitive. Option 2 also creates a vector then uses correct Vector syntax but falls over when the parameter is a primitive instead of an object.
________________________________________

Answer 48)

3) The lower part of the word Dolly will be seen at the top of the form

The Second parameter to the drawstring method indicates where the baseline of the string will be placed. Thus the 3rd parameter of 10 indicates the Y coordinate to be 10 pixels from the top of the Frame. This will result in just the bottom of the string Dolly showing up or possibly only the descending part of the letter y.
________________________________________

Answer 49)

1) Compile time error referring to a cast problem

This is a bit of a sneaky one as the Math.random method returns a pseudo random number between 0 and 1, and thus option 3 is a plausible Answer. However the number returned is a double and so the compiler will complain that a cast is needed to convert a double to an int.
________________________________________

Answer 50)

1) public void ioCall ()throws IOException{

 DataInputStream din = new DataInputStream(System.in);

 din.readChar();

 }

If a method might throw an exception it must either be caught within the method with a try/catch block, or the method must indicate the exception to any calling method by use of the throws statement in its declaration. Without this, an error will occur at compile time.
________________________________________

Answer 51)

3) A compile time error

Because only one instance of a static method exists not matter how many instance of the class exists it cannot access any non static variables. The JVM cannot know which instance of the variable to access. Thus you will get an error saying something like
Can't make a static reference to a non static variable
________________________________________

Answer 52)

2) Create an instance of the GridBagConstraints class, set the weightx field and then pass the GridBagConstraints instance with the component to the setConstraints method of the GridBagLayout class.

The Key to using the GridBagLayout manager is the GridBagConstraint class. This class is not consistent with the general naming conventions in the java API as you would expect that weightx would be set with a method, whereas it is a simple field (variable).

If you have a copy of the Roberts and Heller Java2 Guide that says the exam does not cover the GridBagLayout, this is an error which is corrected in later versions of the book
________________________________________

Answer 53)

2) Return the name of the parent directory

3) Delete a file

It is surprising that you can't change the current directory. It is not so surprising that you can't tell if a file contains text or binary information.
________________________________________

Answer 54)

2) Output of One One Two Two

Answer 3 would would be true if the code called the start method instead of the run method (well it is on my Windows machine anyway, I'm not sure it would be for ever implementation of Java Threads). If you call the run method directly it just acts as any other method and does not return to the calling code until it has finished executing.
________________________________________

Answer 55)

1) You cannot be certain when garbage collection will run

Although there is a Runtime.gc(), this only suggests that the Java Virtual Machine does its garbage collection. You can never be certain when the garbage collector will run. Roberts and Heller is more specific abou this than Boone. This uncertainty can cause consternation for C++ programmers who wish to run finalize methods with the same intent as they use destructor methods.
________________________________________

Answer 56)

4) The fill field of the GridBagConstraints class

Unlike the GridLayout manager you can set the individual size of a control such as a button using the GridBagLayout manager. A little background knowledge would indicate that it should be controlled by a setSomethingOrOther method, but it isn't.

If you have a copy of the Roberts and Heller Java2 Guide that says the exam does not cover the GridBagLayout, this is an error. You can confirm this by looking at the online errata at
________________________________________

Answer 57)

4) A collection for storing bits as on-off information, like a vector of bits

This is the description given to a bitset in Bruce Eckels "Thinking in Java" book. The reference to unique sequence of bits was an attempt to mislead because of the use of the word Set in the name bitset. Normally something called a set implies uniqueness of the members, but not in this context.
________________________________________

Answer 58)

4)Compile error: Superclass Class1.Base of class Class1.Class1 not found

Using the package statement has an effect similar to placing a source file into a different directory. Because the files are in different packages they cannot see each other. The stuff about File1 not having been compiled was just to mislead, java has the equivalent of an "automake", whereby if it was not for the package statements the other file would have been automatically compiled.
________________________________________

Answer 59)

4) Output of Over.amethod()

The names of parameters to an overridden method is not important, but as the version of amethod in class Base is set to be private it is not visible within Over (despite Over extending Base) and thus does not take part in overriding.
________________________________________

Answer 60)

1) Set the gridy value of the GridBagConstraints class to a value increasing from 1 to 4

Answer 4 is fairly obviously bogus as it is the GridBagConstraints class that does most of the magic in laying out components under the GridBagLayout manager. The fill value of the GridBagConstraints class controls the behavior inside its virtual cell and the ipady field controls the internal padding around a component.

If you have a copy of the Roberts and Heller Java2 Guide that says the exam does not cover the GridBagLayout, this is an error. You can confirm this by looking at the online errata at
Answers(2)
________________________________________

Answer 1)
1) The code will compile and run, printing out the words "My Func"
A class that contains an abstract method must be declared abstract itself, but may contain non abstract methods.
________________________________________

Answer 2)
4) The code will compile but will complain at run time that main is not correctly defined
In this example the parameter is a string not a string array as needed for the correct main method
________________________________________

Answer 3)
1) public

2) private

4) transient
The keyword transient is easy to forget as is not frequently used. Although a method may be considered to be friendly like in C++ it is not a Java keyword.
________________________________________

Answer 4)

2) The compiler will complain that the Base class is not declared as abstract.

If a class contains abstract methods it must itself be declared as abstract
________________________________________

Answer 5)

1) To get to access hardware that Java does not know about

3) To write optimised code for performance in a language such as C/C++
________________________________________

Answer 6)

4) Success in compilation and output of "amethod" at run time.

A final method cannot be ovverriden in a sub class, but apart from that it does not cause any other restrictions.
________________________________________

Answer 7)

4) Compilation and execution without error

It would cause a run time error if you had a call to amethod though.

________________________________________

Answer 8)

1)Compile time error: Base cannot be private

A top leve (non nested) class cannot be private.
________________________________________

Answer 9)

4) P1 compiles cleanly but P2 has an error at compile time
The package statement in P1.java is the equivalent of placing the file in a different directory to the file P2.java and thus when the compiler tries to compile P2 an error occurs indicating that superclass P1 cannot be found.
________________________________________

Answer 10)

2) An error at run time
This code will compile, but at run-time you will get an ArrayIndexOutOfBounds exception. This becuase counting in Java starts from 0 and so the 5th element of this array would be i[4].

Remember that arrays will always be initialized to default values wherever they are created.
________________________________________

Answer 11)

2)myarray.length;

The String class has a length() method to return the number of characters. I have sometimes become confused between the two.
________________________________________

Answer 12)

3) A Frame with one large button marked Four in the Centre
The default layout manager for a Frame is the BorderLayout manager. This Layout manager defaults to placing components in the centre if no constraint is passed with the call to the add method.
________________________________________

Answer 13)

4) Do nothing, the FlowLayout will position the component
________________________________________

Answer 14)

1) Use the setLayout method
________________________________________

Answer 15)

1) ipadx

2) fill

3) insets
________________________________________

Answer 16)

2) The buttons will run from left to right along the top of the frame

The call to the setLayout(new FlowLayout()) resets the Layout manager for the entire frame and so the buttons end up at the top rather than the bottom.
________________________________________

Answer 17)

2) It is a field of the GridBagConstraints class for controlling component placement

3) A valid settting for the anchor field is GridBagconstraints.NORTH
________________________________________

Answer 18)

4) Clean compile but no output at runtime


This is a bit of a sneaky one as I have swapped around the names of the methods you need to define and call when running a thread. If the for loop were defined in a method called public void run() and the call in the main method had been to b.start() The list of values from 0 to 9 would have been output.
________________________________________

Answer 19)

2) false

You can re-use the same instance of the GridBagConstraints when added successive components.
________________________________________

Answer 20)

4) An interface that ensures that implementing classes cannot contain duplicates
________________________________________

Answer 21)

2) The add method returns false if you attempt to add an element with a duplicate value
I find it a surprise that you do not get an exception.
________________________________________

Answer 22)

1) The program exits via a call to exit(0);

2) The priority of another thread is increased

3) A call to the stop method of the Thread class

Note that this question asks what can cause a thread to stop executing, not what will cause a thread to stop executing. Java threads are somewhat platform dependent and you should be carefull when making assumptions about Thread priorities. On some platforms you may find that a Thread with higher priorities gets to "hog" the processor. You can read up on this in more detail at
________________________________________

Answer 23)

4) The class can only access final variables
________________________________________

Answer 24)

1) To call from the currently running thread to allow another thread of the same or higher priority to run
Option 3 looks plausible but there is no guarantee that the thread that grabs the cpu time will be of a higher priority. It will depend on the threading algorithm of the Java Virtual Machine and the underlying operating system
________________________________________

Answer 25)

4) Compilation and running with output 0 to 9
________________________________________

Answer 26)

1) None of these options

Because of the lack of a break statement after the break 10; statement the actual output will be

"ten" followed by "twenty"
________________________________________

Answer 27)

4) System.gc();
________________________________________

Answer 28)

1) Compilation succeeds and at run time an output of 0 and false

The default value for a boolean declared at class level is false, and integer is 0;
________________________________________

Answer 29)

1) Compile time error
You will get an error saying something like "Cant make a static reference to a non static variable". Note that the main method is static. Even if main was not static the array argv is local to the main method and would thus not be visible within amethod.
________________________________________

Answer 30)

3) Output of "Not equal"
Despite the actual character strings matching, using the == operator will simply compare memory location. Because the one string was created with the new operator it will be in a different location in memory to the other string.
________________________________________

Answer 31)

4) Compile and run with output of "Pausing" and "Continuing" after a key is hit
An overriden method in a sub class must not throw Exceptions not thrown in the base class. In the case of the method amethod it throws no exceptions and will thus compile without complain. There is no reason that a constructor cannot be protected.
________________________________________

Answer 32)

4) Compile time error because of the line creating the instance of Inner


This looks like a question about inner classes but it is also a reference to the fact that the main method is static and thus you cannot directly access a non static method. The line causing the error could be fixed by changing it to say
        Inner i = new Outer().new Inner();


Then the code would compile and run producing the output "Inner"
________________________________________

Answer 33)

1) Error at compile time
________________________________________

Answer 34)

4) Compile time error
An error will be caused by attempting to define an integer as static within a method. The lifetime of a field within a method is the duration of the running of the method. A static field exists once only for the class. An approach like this does work with Visual Basic.
________________________________________

Answer 35)

4)int z = 015;
The letters c and s do not exist as literal indicators and a String must be enclosed with double quotes, not single as in this case.
________________________________________

Answer 36)

1)double

4)instanceof

Note the upper case S on switch means it is not a keyword and the word then is part of Visual Basic but not Java. Also, instanceof looks like a method but is actually a keyword,
________________________________________

Answer 37)

4) -3.0
________________________________________

Answer 38)

3) one
Command line parameters start from 0 and from the first parameter after the name of the compile (normally Java)
________________________________________

Answer 39)

4) The Set is designed for unique elements.
Collection is an interface, not a class. The Collection interface includes a method called iterator. This returns an instance of the Iterator class which has some similarities with Enumerators.

The name set should give away the purpose of the Set interface as it is analogous to the Set concept in relational databases which implies uniquness.
________________________________________

Answer 40)

2) If multiple listeners are added to a component the events will be processed for all but with no guarantee in the order
4) You may remove as well add listeners to a component.
It ought to be fairly intuitive that a component ought to be able to have multiple listeners. After all, a text field might want to respond to both the mouse and keyboard
________________________________________

Answer 41)

1) b=m;

3) d =i;
You can assign up the inheritance tree from a child to a parent but not the other way without an explicit casting. A boolean can only ever be assigned a boolean value.
________________________________________

Answer 42)

2) You can obtain a mutually exclusive lock on any object

3) A thread can obtain a mutually exclusive lock on an object by calling a synchronized method on that object.

4) Thread scheduling algorithms are platform dependent
Yes that says dependent and not independent.
________________________________________

Answer 43)

2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type
This question is about the requirement to understand the difference between the "is-a" and the "has-a" relationship. Where a class is inherited you have to ask if it represents the "is-a" relationship. As the difference between the root and the two children are the operating system you need to ask are Linux and Windows types of computers.The answer is no, they are both types of Operating Systems. So option two represents the best of the options. You might consider having operating system as an interface instead but that is another story.
________________________________________

Answer 44)

1) An inner class may be defined as static

4) An inner class may extend another class
A static inner class is also sometimes known as a top level nested class. There is some debate if such a class should be called an inner class. I tend to think it should be on the basis that it is created inside the opening braces of another class. How could a programmer provide a constructor for an anonymous class?. Remember a constructor is a method with no return type and the same name as the class. Inner classes may be defined as private
________________________________________

Answer 45)

4) Compilation and output of "Not equal! 10"
The output will be "Not equal 10".  This illustrates that the Output +=10 calculation was never performed because processing stopped after the first operand was evaluated to be false. If you change the value of b1 to true processing occurs as you would expect and the output is "We are equal 20";.
________________________________________

Answer 46)

2)j= i<<j;

4)j=i<<l;
________________________________________
Answer 47)
4) 12
As well as the binary OR objective this questions requires you to understand the octal notation which means that the leading letter zero (not the letter O)) means that the first 1 indicates the number contains one eight and nothing else. Thus this calculation in decimal mean
8|4


To convert this to binary means
1000


0100

----

1100

----

Which is 12 in decimal
The | bitwise operator means that for each position where there is a 1, results in a 1 in the same position in the answer.
________________________________________

Answer 48)

2)s+=i;
Only a String acts as if the + operator were overloaded
________________________________________

Answer 49)

Although the objectives do not specifically mention the need to understand the I/O Classes, feedback from people who have taken the exam indicate that you will get questions on this topic. As you will probably need to know this in the real world of Java programming, get familiar with the basics. I have assigned these questions to Objective 10.1 as that is a fairly vague objective.
1) File f = new File("/","autoexec.bat");

2) DataInputStream d = new DataInputStream(System.in);

3) OutputStreamWriter o = new OutputStreamWriter(System.out);
Option 4, with the RandomAccess file will not compile because the constructor must also be passed a mode parameter which must be either "r" or "rw"
________________________________________

Answer 50)

1)o1=o2;

2)b=ob;

4)o1=b;
________________________________________

Answer 51)

4) 10020
In the call
another(v,i);
A reference to v is passed and thus any changes will be intact after this call.
________________________________________

Answer 52)

1) public void amethod(String s, int i){}

4) public void Amethod(int i, String s) {}
Overloaded methods are differentiated only on the number, type and order of parameters, not on the return type of the method or the names of the parameters.
________________________________________

Answer 53)


4)Base b = new Base(10);
Any call to this or super must be the first line in a constructor. As the method already has a call to this, no more can be inserted.
________________________________________

Answer 54)
1) System.out.println(s);

4) System.out.println(iArgs);
A class within a method can only see final variables of the enclosing method. However it the normal visibility rules apply for variables outside the enclosing method.
________________________________________

Answer 55)

1) yield()

2) sleep

4) stop()
Note, the methods stop and suspend have been deprecated with the Java2 release, and you may get questions on the exam that expect you to know this. Check out the Java2 Docs for an explanation
________________________________________

Answer 56)

1) addElement
________________________________________

Answer 57)

The import statement allows you to use a class directly instead of fully qualifying it with the full package name, adding more classess with the import statement does not cause a runtime performance overhad. I assure you this is true. An inner class can be defined with the protected modifier, though I am not certain why you would want to do it. An inner class can be defined with the private modifier, try compiling some sample code before emailing me to ask about this.
3)A inner class may under some circumstances be defined with the protected modifier

4) An interface cannot be instantiated
________________________________________
Answer 58)
1) mousePressed(MouseEvent e){}

4) componentAdded(ContainerEvent e){}
________________________________________

Answer 59)

1) iterator

2) isEmpty

3) toArray
________________________________________

Answer 60)

2) Ensures only one thread at a time may access a method or object
________________________________________

End of document

Answers(3)

Answer to Question 1)

1) float f=1/3;

2) int i=1/3;

4) double d=999d;
The fact that option 3 does not compile may be a surprise. The problem is because the default type for a number with a decimal component is a double and not a float. The additional trailing d in the option with 999 doesn't help, but it doesn't harm.
________________________________________

Answer to Question 2)
2) new
The option NULL (note the upper case letter) is definitely not a keyword. There is some discussion as to i. There is some discussion as to if null is a keyword but for the purpose of the exam you should probably assume it is a keyword.
The option instanceOf is a bit of a misleading option that would probably not occur on the exam. The real keyword is instanceof (note that the of has no capital letter O). I had the incorrect version in an earlier version of this tutorial as it looks more likely to my eyes. The instanceof keyword looks like a method, but it is actually an operator.
The option wend is probably valid in some other language to indicate the end of a while loop, but Java has no such keyword.
________________________________________

Answer to Question 3)
1) System.out.println(1+1);

2) int i=2+'2';

Option 3 is not valid because single quotes are used to indicate a character constant and not a string. Several people have emailed me to say that option 3 will compile. When they eventually compiled the exact code they have agreed, it will not compile. Let me re-state that
String s="on"+'one';
Will NOT compile.
Option 4 will not compile because 255 is out of the range of a byte
________________________________________

Answer to Question 4)
1) The garbage collection algorithm in Java is vendor implemented
Threading and garbage collection are two of the few areas that are platform dependent. This is one of the

reasons why Java is not suitable for realtime programming. It is not a good idea use it to control your

plane or nuclear power station. Once an instance of the Integer class has a value it cannot be changed.
________________________________________

Answer to Question 5)
(Not on the official sub objectives but this topic does come up on the exam)
2) The RandomAccessFile class allows you to move directly to any point a file.

4) The characteristics of an instance of the File class such as the directory separator, depend on the current underlying operating system
The File class can be considered to represent information about a file rather than a real file object. You can create a file in the underlying operating system by passing an instance of a file to a stream such as FileOutputStream. The file will be created when you call the close method of the stream.
________________________________________

Answer to Question 6)
2) The instanceof operator can be used to determine if a reference is an instance of a particular primitive wrapper class

 
The instanceof operator can only be used to make a static comparison with a class type. Java1.1 added the isInstance method to the class Class to allow you to dynamically determine a class type. The exam does not test you on isInstance.
________________________________________

Answer to Question 7)
2) Interfaces cannot have constructors
If you try to create a constructor for an Interface the compiler will give you an error message something like
"interface can't have constructors".
4) Interfaces are the Java approach to addressing the single inheritance model, but require implementing classes to create the functionality of the Interfaces.
An interface may contain variables as well as methods. However any variables are final by default and must be assigned values on creation. A class can only extend one other class (single inheritance) but may implement as many interfaces as you like (or is sensible).
________________________________________

Answer to Question 8)
None of these are valid statements. The Math class is final and cannot be extended. The max method takes two parameters, round only takes one parameter and there is no mod parameter. You may get questions in the exam that have no apparently correct answer. If you are absolutely sure this is the case, do not check any of the options.
________________________________________

Answer to Question 9)
1) The Runnable interface has only one method run that needs to be created in any class that implements it. The start method is used to actually call and start the run method executing.
________________________________________

Answer to Question 10)
1) A byte can represent between -128 to 127
The char type is the only unsigned type in Java and thus cannot represent a negative number.
For more information on this topic go to
________________________________________

Answer to Question 11)
2) Compilation and no output at runtime
Because the method in Base called Base has a return type it is not a constructor and there for does not get called on creation of an instance of its child class In
For more information on this topic go to
________________________________________

Answer to Question 12)
4) Compilation and output of hello
This type of question is particularly calculated to catch out C/C++ programmers who might expect parameter zero to be the name of the compiler.
For more information on this topic go to
________________________________________

Answer to Question 13)
1) If a class has any abstract methods it must be declared abstract itself.

3) The final modifier means that a class cannot be sub-classed

4) transient and volatile are Java modifiers
An abstract class may have non abstract methods. Any class that descends from an abstract class must implement the abstract methods of the base class or declare them as abstract itself.
For more information on this topic go to
________________________________________

Answer to Question 14)
2) public static void amethod(){}

4) static native void amethod();
Option 1 is not valid because it has braces and the native modifier means that the method can have no body. This is because the body must be implemented in some other language (often C/C++). Option 3 is not valid because private and protected contradict themselves.
For more information on this topic go to
________________________________________

Answer to Question 15)
4) Constructors are not inherited
Constructors can be marked public, private or protected. Constructors do not have a return type.
For more information on this topic go to
________________________________________

Answer to Question 16)

2) Compile time error
An error occurs when the class Severn attempts to call the zero parameter constructor in the class Base Because the Base class has an integer constructor Java does not provide the "behind the scenes" zero parameter constructor.
For more information on this topic go to
________________________________________

Answer to Question 17)
1) static methods do not have access to the implicit variable called this

2) A static method may be called without creating an instance of its class

3) a static may not be overriden to be non-static
The implicit variable this refers to the current instance of a class and thus and by its nature a static method cannot have access to it.
For more information on this topic go to
________________________________________

Answer to Question 18)
1)
char c='1';

System.out.println(c>>1);
4)
int i=1;

System.out.println(i<<1);

 
For more information on this topic go to
________________________________________

Answer to Question 19)
2) An event listener may be removed from a component
3) The ActionListener interface has no corresponding Adapter class
A component may have multiple event listeners attached. Thus a field may need to respond to both the mouse and the keyboard, requiring multiple event handlers. The ActionListener has not matching Adapter class because it has only one method, the idea of the Adapter classes is to eliminate the need to create blank methods.
For more information on this topic go to
________________________________________

Answer to Question 20)
3) transient

4) volatile

 
Option 1, sizeof is designed to catch out the C/C++ programmers. Java does not have a sizeof keyword as the size of primitives should be consistent on all Java implementations. Although a program needs a main method with the standard signature to start up it is not a keyword. The real keywords are less commonly used and therefore might not be so familiar to you.
For more information on this topic go to
________________________________________

Answer to Question 21)
3) The default constructor takes no parameters

4) The default constructor is not created if the class has any constructors of its own.
Option 1 is fairly obviously wrong as constructors never have a return type. Option 2 is very dubious as well as Java does not offer void as a type for a method or constructor.
For more information on this topic go to
________________________________________

Answer to Question 22)
1) All of the variables in an interface are implicitly static

2) All of the variables in an interface are implicitly final

3) All of the methods in an interface are implictly abstract
All the variables in an interface are implicitly static and final. Any methods in an interface have no body, so may not access any type of variable
________________________________________

Answer to Question 23)
2) The + operator is overloaded for concatenation for the String class
In Java Strings are implemented as a class within the Java.lang package with the special distinction that the + operator is overloaded. If you thought that the String class is implemented as a char array, you may have a head full of C/++ that needs emptying. There is not "wrapper class" for String as wrappers are only for primitive types.
If you are surprised that option 4 is not a correct answer it is because length is a method for the String class, but a property for and array and it is easy to get the two confused.
________________________________________

Answer to Question 24)
1) A method in an interface must not have a body

3) A class may extends one other class plus many interfaces
A class accesses an interface using the implements keyword (not uses)
________________________________________

Answer to Question 25)
3) The following statement will produce a result of zero, System.out.println(1 >>1);
Although you might not know the exact result of the operation -1 >>> 2 a knowledge of the way the bits will be shifted will tell you that the result is not plus 1. (The result is more like 1073741823 ) There is no such Java operator as the unsigned left shift. Although it is normally used for storing characters rather than numbers the char Java primitive is actually an unsigned integer type.

And for information on the size of primitives see
________________________________________

Answer to Question 26)
2) Arrays elements are initialized to default values wherever they are created using the keyword new.

You can find the size of an array using the length field. The method length is used to return the number of characters in a String. An array can contain elements of any type but they must all be of the same type. The size of an array is fixed at creation. If you want to change its size you can of course create a new array and assign the old one to it. A more flexible approach can be to use a collection class such as Vector.
________________________________________

Answer to Question 27)
2) Output of "Hello Crowle"
This code is an example of a short circuited operator. Because the first operand of the || (or) operator returns true Java sees no reason to evaluate the second. Whatever the value of the second the overall result will always be true. Thus the method called place is never called.
________________________________________

Answer to Question 28)
4) none of the above;
You may access methods of a direct parent class through the use of super but classes further up the hierarchy are not visible
________________________________________

Answer to Question 29)
2) A method with the same name completly replaces the functionality of a method earlier in the hierarchy
Option 3 is more like a description of overloading. I like to remind myself of the difference between overloading and overriding in that an overriden method is like something overriden in the road, it is squashed, flat no longer used and replaced by something else. An overloaded method has been given extra work to do (it is loaded up with work), but it is still being used in its original format. This is just my little mind trick and doesn't match to anything that Java is doing.
________________________________________

Answer to Question 30)
2) The / operator is used to divide one value by another

3) The # symbol may not be used as the first character of a variable
The % is the modulo operator and returns the remainder after a division. Thus 10 % 3=1

The $ symbol may be used as the first character of a variable, but I would suggest that it is generally not a good idea. The # symbol cannot be used anywhere in the name of a variable. Knowing if a variable can start with the # or $ characters may seem like arbitrary and non essential knowlege but questions like this do come up on the exam.
________________________________________

Answer to Question 31)
1) The default layout manager for an Applet is FlowLayout

4) The FlowLayout manager attempts to honor the preferred size of any components
The default layout manager fror an Application is BorderLayout. An applet will use the default of FlowLayout if one is not specifically applied
________________________________________

Answer to Question 32)
3) Only one instance of a static variable will exist for any amount of class instances
Option 1) is more a description of a final variable. Option 2 is designed to fool Visual Basic programmers like me as this is how you can use the keyword static in VB. The modifier static can be applied to a class (only an innner class) , method or variable.
________________________________________

Answer to Question 33)
1) Java uses a system called UTF for I/O to support international character sets

3) An instance of FileInputStream may not be chained to an instance of FileOutputStream
4) File I/O activities requires use of Exception handling
Internally Java uses Unicode which are 16 bit characters. For I/O Java uses UTF which may be more thatn 16 bits per chamore thatn 16 bits per character.

Generally InputStreams can only be chained to other InputStreams and OutputStreams can only be chained to other OutputStreams. The piped streams are an exception to this.
________________________________________

Answer to Question 34)
1) Compile time error
It wil produce an error like "Abstract and native method can't have a body. This is typical of the more misleading question where you might think it is asking you about the circumstances under which the finally clause runs, but actually it is about something else.
________________________________________

Answer to Question 35)
2) Compilation and run with the output "Running"
This is perfectly legitimate if useless sample of creating an instnace of a Thread and causing its run method to execute via a call to the start method. The Thread class is part of the core java.lang package and does not need any explicit import statement. The reference to a Thread target is an attempt to mislead with a reference to the method of using the Runnable interface instead of simply inheriting from the Thread super class.
________________________________________

Answer to Question 36)
1) RandomAccessFile raf=new RandomAccessFile("myfile.txt","rw");
The RandomAccessFile is an anomaly in the Java I/O architecture. It descends directly from Object and is not part of the Streams architecture
________________________________________

2) public int amethod(int i, int j) {return 99;}

3) protected void amethod (long l){}

4) private void anothermethod(){}
Option 1 will not compile on two counts. One is the obvious one that it claims to return an integer. The other is that it is effectivly an attempt to redefine a method within the same class. The change of name of the parameter from i to z has no effect and a method cannot be overriden within the same class.
________________________________________

Answer to Question 38)
1) Code must be written to cause a frame to close on selecting the system close menu

2) The default layout for a Frame is the BorderLayout Manager

4) The GridBagLayout manager makes extensive use of the the GridBagConstraints class.
You can change the layout manager for a Frame or any other container whenever you like
________________________________________

Answer to Question 39)
4) The code will compile without error
There are no restrictions on the level of nesting for inner/nested classes. Inner classes may be marked private. The main method is not declared as public static void main, and assuming that the commandline was java Droitwich it would not be invoked anyway.
________________________________________

Answer to Question 40)
1) super.oak=1;

2) oak=33;

3) Base.oak=22;
Because the variable oak is declared as static only one copy of it will exist. Thus it can be changed either through the name of its class or through the name of any instance of that class. Because it is created as an integer it canot be assigned a fractional component without a cast.
________________________________________

Answer to Question 41)
Obje Question 41)
4) Use the getText method of a Textfield and use the parseInt method of the Integer class
Here is an example of how you might do this
Integer.parseInt(txtInputValue.getText());
I'm not sure that a question on this actually will come up in the exam but it is a very useful thing to know in the real world.
________________________________________

Answer to Question 42)
4) none of the above
The wrapper classes are immutable. Once the value has been set it cannot be changed. A common use of the wrapper classes is to take advantage of their static methods such as Integer.parseInt(String s) that will returns an integer if the the value has been set it cannot be changed. A common use of the wrapper classes is to take advantage of their static methods such as Integer.parseInt(String s) that will returns an integer if the String contains one.
________________________________________

Answer to Question 43)
2) constructors cannot be overriden
Overloading constructors is a key technique to allow multiple ways of initialising classes. By definition, constructors have have no return values so option 3 makes no sense. Option 4 is the inverse of what happens as constructor code will execute starting from the oldest ancestor class downwards. You can test this by writing a class that inherits from a base class and getting the constructor to print out a message. When you create the child class you will see the order of constructor calling.
________________________________________

Answer to Question 44)
yield is a static method and causes whatever thread is currently executing to yield its cycles.
1) t.yield();

2) Thread.yield()
(Thanks Roseanne )

JavaDoc for the Thread class
________________________________________

Answer to Question 45)
4) Compilation and run with an output of 99
The fact that the variable court is declared as private does not stop the constructor from being able to initialise it.
________________________________________

Answer to Question 46)
3) To be overriden a method must have the same name, parameter and return types
Option 1 is a sneaky one in that it should read overriden not overloaded. An overriden method must also have the same return type. Parameter names are purely a programmer convenience and are not a factor in either overloading and overriding. Parameter order is a factor however.
________________________________________

Answer to Question 47)
1) Compile time error
With the sun JDK it will produce the following error
"Only constructors can invoke constructors".
If you took out the call to super that causes this error the program would compile and at runtime it would output Base and then Checket as constructors are called from the oldest ancestor class downwards.
________________________________________

Answer to Question 48)
1) Static methods cannot be overriden to be non static
________________________________________

Answer to Question 49)
2) A program can suggest that garbage collection be performed but not force it
4) A reference becomes eligable for garbage collection when it is assigned to null
If a program keeps creating new references without any being discarded it may run out of memory. Unlike most aspects of Java garbage collection is platform dependent.
________________________________________

Answer to Question 50)
2) Compile time error
The main method is static and cannot access the non static variable x
________________________________________

Answer to Question 51)
1) Compile time error
When compiled with JDK 1.1 the following error is produced.
Abstract and native methods can't have a body: void hallow() abstract void hallow()
________________________________________

Answer to Question 52)
3) Create and employee class with fields for Job title and fields for the other values.
These questions can appear tricky as the whole business of designing class structures is more art than science. It is asking you to decide if an item of data is best represented by the "Is a" or "Has a" relationship. Thus in this case any of the job titles mentioned will always refer to something that "Is a" employee. However the employee "has a" job title that might change.
One of the important points is to ask yourself when creating a class "Could this change into another class at some point in the future". Thus in this example an apprentice chef would hope one day to turn into a chef and if she is very good will one day be head chef. Few other mock exams seem to have this type of questions but they di come up in the real exam.
________________________________________

Answer to Question 53)
3) new BufferedReader(new InputStreamReader(new FileInputStream("file.name")));
The key to this question is that it asks about tens of megabytes of data, implying that performance is an issue. A Buffered Reader will optimise the performance of accessing a file. Although the objectives do not specifically mention it questions on I/O do come up on the exam.
________________________________________

Answer to Question 54)
4) Output of 0
The method fermin only receives a copy of the variable i and any modifications to it are not reflected in the version in the calling method. The post increment operator ++ effectivly modifes the value of i after the initial value has been assiged to the left hand side of the equals operator. This can be a very tricky conept to understand
________________________________________

Answer to Question 55)
1) Compile time error
This might be considered a "gocha" or deliberate attempt to mislead you because i has been given the data type of long and the parameter must be of long and the parameter must be either a byte, char, short or int. If you attempt to compile this code with JDK 1.2 you will get an error that says something like "Incompatible type for switch, Explicit cast needed to convert long to int". Answering with option 2 would have been reasonable because if the parameter had been an integer type the lack of break statements would have caused this output. If you gave either of the answers you should probably revise the subject.
________________________________________

Answer to Question 56)
1) System.out.println(i++);

3) System.out.println(i);

4) System.out.println(i==);
________________________________________

Answer to Question 57)
4) System.out.println( ((Agg) a).getFields());
The Base type reference to the instance of the class Agg needs to be cast from Base to Agg to get access to its methods.The method invoked depends on the object itself, not on the declared type. So, a.getField() tries to invoke a getField method in Base which does not exist. But the call to ((Agg)a).getField() will invoke the getField() in the Agg class. You will be unlucky to get a question as complex as this on the exam. If you think option 1 is valid, have a go at compiling the code.
________________________________________

Answer to Question 58)
2) compilation and output of false
A variable defined at class level will always be given a default value and the default value for the primitive type boolean is false
________________________________________

Answer to Question 59)
1) The x,y coordinates of an instance of MouseEvent can be obtained using the getX() and getY() methods

4) The time of a MouseEvent can be extracted using the getWhen method
If you chose option 4, referring to the mythical getTime method you have made a reasonable guess based on the normal conventions of Java. However the conventions do not always hold true. If you chose option 3 perhaps you are not as aware of the conventions as you should be.
________________________________________

Answer to Question 60)
2) The program will run and output only "fliton"
This question tests your knowledge of the principle that the finally clause will almost always run.

posted on 2006-11-16 21:18 lbfeng 阅读(714) 评论(0)  编辑  收藏 所属分类: 专业考试题库

只有注册用户登录后才能发表评论。


网站导航: