Some Java questions for Sun Certification
By: Abhishek
Ques: Given the following code what will be the output?
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.println(v.i);
}//End of amethod
public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.println(v.i+ " "+i);
}//End of another
}
1) 10,0,30
2) 10,0,10
3) 20,99,30
4) 10,0,20
Ans: In the call another(v,i) a reference to v is passed and thus any changes will be intact after this call. However v = vh will only change the reference to v in that block and when the method returns v will not be referring to vh. So the answer is 4. (10,0,20)
Ques: Which of the following are methods of the
Collection interface?
1) iterator
2) isEmpty
3) toArray
4) setText
Ans: 1,2,3
Ques: What will happen when you attempt to compile and run this code?
public class Mod{
public static void main(String argv[]){
}
public static native void amethod();
}
1) Error at compilation: native method cannot be
static
2) Error at compilation native method must return value
3) Compilation but error at run time unless you have made code containing native amethod
available
4) Compilation and execution without error
Ans: Since the native method is not being called anywhere the answer is 4. If the native method was being invoked from main then answer would have been 3. Eg take a look at this code:
public class Mod{
public static void main(String argv[]){
Mod.amethod();
}
public static native
void amethod();
}
If you compile this, there will be no error. But if
you run this you get:
java.lang.UnsatisfiedLinkError: amethod
at Mod.main(Mod.java:3)
Ques: Which of the following are fields of the GridBagConstraints class?
1) ipadx
2) fill
3) insets
4) width
Ans: 1,2,3
Ques: Which statements are correct about the anchor field?
1) It is a field of the GridBagLayout manager for
controlling component placement
2) It is a field of the GridBagConstraints class for controlling component placement
3) A valid setting for the anchor field is GridBagConstraints.NORTH
4) The anchor field controls the height of components added to a container
Ans: 2,3
Ques: What can cause a thread to stop executing?
1) The program exits via a call to System.exit(0);
2) Another thread is given a higher priority
3) A call to the thread's stop method.
4) A call to the halt method of the Thread class
Ans: 1,2,3
Ques: What will happen when you attempt to compile and run this program
public class Outer{
public String name = "Outer";
public static void main(String argv[]){
Inner i = new Inner();
i.showName();
}//End of main
private class Inner{
String name =new String("Inner");
void showName(){
System.out.println(name);
}
}//End of Inner class
}
1) Compile and run with output of "Outer"
2) Compile and run with output of "Inner"
3) Compile time error because Inner is declared as private
4) Compile time error because of the line creating the instance of Inner
Ans: 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". So correct
answer is 4
Ques: Given the following variables which of the following lines will compile without error?
String s = "Hello"; long l = 99; double d = 1.11; int i = 1; int j = 0; 1) j= i <<s; 2) j= i<<j; 3) j=i<<d; 4) j=i<<l;
Ans: 2,4. Note that if you do something like this: j = l << i; You will get compile error: Incompatible type for =. Explicit cast needed to convert long to int. j = l << i;
Ques: Given the folowing classes which of the following will compile without error?
interface IFace{}
class CFace implements IFace{}
class Base{}
public class ObRef extends Base{
public static void main(String argv[]){
ObRef ob = new ObRef();
Base b = new Base();
Object o1 = new Object();
IFace o2 = new CFace();
}
}
1)o1=o2;
2)b=ob;
3)ob=b;
4)o1=b;
Ans: 1,2,4
Ques: Which of the following are legal identifiers
1) 2variable
2) variable2
3) _whatavariable
4) _3_
5) $anothervar
6) #myvar
Ans: 2,3,4,5
Ques: What will happen if you try to compile and run the following code?
public class Q {
public static void main(String argv[]){
int anar[]=new int[5];
System.out.println(anar[0]);
}
}
1) Error: anar is referenced before it is initialized
2) null
3) 0
4) 5
Ans: Arrays are always initialised when they are created. As this is an array of ints it will be initalised with zeros. So ans is 3.
Ques: What will happen when you attempt to compile and run the following code?.
1) It will compile and the run method will print out
the increasing value of i.
2) It will compile and calling start will print out the increasing value of i.
3) The code will cause an error at compile time.
4) Compilation will cause an error because while cannot take a parameter of true.
class Background implements Runnable{
int i=0;
public int run(){
while(true){
i++;
System.out.println("i="+i);
} //End while
return 1;
}//End run
}//End class
Ans: The code will cause an error at compile time. so ans is 3. The error is caused because run should have a void not an int return type. Any class that is implements an interface must create a method to match all of the methods in the interface. The Runnable interface has one method called run that has a void return type.The sun compiler gives the error Method redefined with different return type: int run() was defined as void run();
Ques: Given the following code how could you invoke the Base constructor that will print out the string "base constructor";
class Base{
Base(int i){
System.out.println("base constructor");
}
Base(){
}
}
public class Sup extends Base{
public static void main(String argv[]){
Sup s= new Sup();
//One
}
Sup()
{
//Two
}
public void derived()
{
//Three
}
}
1) On the line After //One put Base(10);
2) On the line After //One put super(10);
3) On the line After //Two put super(10);
4) On the line After //Three put super(10);
Ans: On the line After //Two put super(10). Ans is 3;
Constructors can only be invoked from within constructors.
Ques: Which of the following will successfully create an instance of the Vector class and add an element?
1) Vector v=new Vector(99);
v[1]=99;
2) Vector v=new Vector();
v.addElement(99);
3) Vector v=new Vector();
v.add(99);
4 Vector v=new Vector(100);
v.addElement("99");
Ans: 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. Ans is 4.
Ques: Which of the following can you perform using the File class?
1) Change the current directory
2) Return the name of the parent directory
3) Delete a file
4) Find if a file contains text or binary information
Ans: 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. Ans is 2 3.
Ques: You have these files in the same directory. What will happen when you attempt to compile and run Class1.java if you have not already compiled Base.java
//Base.java
package Base;
class Base{
protected void amethod(){
System.out.println("amethod");
}//End of amethod
}//End of class base
package Class1;
//Class1.java
public class Class1 extends Base{
public static void main(String argv[]){
Base b = new Base();
b.amethod();
}//End of main
}//End of Class1
1) Compile Error: Methods in Base not found
2) Compile Error: Unable to access protected method in base class
3) Compilation followed by the output "amethod"
4)Compile error: Superclass Class1.Base of class Class1.Class1 not found
Ans: 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. Ans is 4.
Ques: Which of the following are true?
1) A component may have only one event listener
attached at a time
2) An event listener may be removed from a component
3) The ActionListener interface has no corresponding Adapter class
4) The processing of an event listener requires a try/catch block
Ans: 2,3
Ques: Which of the following are legal statements?
1) float f=1/3;
2) int i=1/3;
3) float f=1.01;
4) double d=999d;
5) int i = 2 + 2;
6) char c = 2 + 2;
Ans: 1,2,4,5,6
Ques: Which of the following statements are true?
1) static methods do not have access to the implicit
variable called this
2) a static method may not be overriden
3) a static method may not be overriden to be non-static
4) a static method may not be overloaded
Ans: 1,3
Ques: Which of the following are Java keywords?
1) sizeof
2) main
3) transient
4) volatile
Ans: 3,4. main is NOT a java key word !!
Ques: Which of the following statements are true?
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 implicitly abstract
4) A method in an interface can access class level variables
Ans: 1,2,3
Ques: Which of the following statements are true?
1) The following statement will produce a result of
1. System.out.println( -1 >>>2);
2) Performing an unsigned left shift (<<<) on a negative number will always
produce a negative number result
3) The following statement will produce a result of zero, System.out.println(1 >>1);
4) All the integer primitives in java are signed numbers
Ans: 3. char is considered to be an int primitive and it is the only unsigned int primitive in java.
Ques: Which of the following statements are true?
1) The default layout manager for an Applet is
FlowLayout
2) The default layout manager for a Frame is FlowLayout
3) A layout manager must be assigned to an Applet before the setSize method is called
4) The FlowLayout manager attempts to honor the preferred size of any components
Ans: 1,4. The default layout manager fror an Application is BorderLayout. An applet will use the default of FlowLayout if one is not specifically applied.
Ques: Which of the following statements are true
about a variable created with the static modifier?
1) Once assigned the value of a static variable may not be altered
2) A static variable created in a method will keep the same value between calls
3) Only one instance of a static variable will exist for any amount of class instances
4) The static modifier can only be applied to a primitive value
Ans: 3. 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, method or variable.
Ques: Which of the following statements are true?
1) Java uses a system called UTF for I/O to support
international character sets
2) The RandomAccessFile is the most suitable class for supporting 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
Ans: 1,3,4
Ques: Assuming any exception handling has been set up, which of the following will create an instance of the RandomAccessFile class
1) RandomAccessFile raf=new
RandomAccessFile("myfile.txt","rw");
2) RandomAccessFile raf=new RandomAccessFile( new DataInputStream());
3) RandomAccessFile raf=new RandomAccessFile("myfile.txt");
4) RandomAccessFile raf=new RandomAccessFile( new File("myfile.txt"));
Ans: 1. The RandomAccessFile is an anomaly in the Java I/O architecture. It descends directly from Object and is not part of the Streams architecture. It requires the access mode, there is no default for it.
Ques: Which of the following statements are true?
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 BoarderLayout Manager
3) The layout manager for a Frame cannot be changed once it has been assigned
4) The GridBagLayout manager makes extensive use of the the GridBagConstraints class.
Ans: 1,2,4
Ques: Given the following code
class Base{
static int oak=99;
}
public class Doverdale extends Base{
public static void main(String argv[]){
Doverdale d = new Doverdale();
d.amethod();
}
public void amethod(){
//Here
}
}
Which of the following if placed after the comment //Here, will compile and modify the value of the variable oak?
1) super.oak=1;
2) oak=33;
3) Base.oak=22;
4) oak=50.1;
Ans: 1,2,3
Ques: Which of the following statements are true
1) constructors cannot be overloaded
2) constructors cannot be overridden
3) a constructor can return a primitive or an object reference
4) constructor invocation occurs from the current class up the hierarchy to the ancestor
class
Ans: 2,4
Ques: Given a reference called t to to a class which extends Thread, which of the following will cause it to give up cycles to allow another thread to execute.
1) t.yield();
2) yield()
3) yield(100) //Or some other suitable amount in milliseconds
4) yield(t);
Ans: 2. Note that yield and sleep are the only static methods of Thread class.
Ques: Which of the following statements are true?
1) A method cannot be overloaded to be less public in
a child class
2) To be overridden a method must have the same name and parameter types
3) To be overridden a method must have the same name, parameter and return types
4) An overridden method must have the same name, parameter names and parameter types
Ans: 3
Ques: You need to read in the lines of a large text file containing tens of megabytes of data. Which of the following would be most suitable for reading in such a file
1) new FileInputStream("file.name")
2) new InputStreamReader(new FileInputStream("file.name"))
3) new BufferedReader(new InputStreamReader(new FileInputStream("file.name")));
4) new RandomAccessFile raf=new RandomAccessFile("myfile.txt","+rw");
Ans: 3. 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.
Ques: What will happen when you attempt to compile and run the following code?
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}
1) Compile time error
2) Output of 2
3) Output of 1
4) Output of 0
Ans: 4. 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
Ques: Given the following code
class Base {}
class Agg extends Base{
public String getFields(){
String name = "Agg";
return name;
}
}
public class Avf{
public static void main(String argv[]){
Base a = new Agg();
}
}
What code placed after the comment //Here will result in calling the getFields method of Base resulting in the output of the string "Agg"?
1) System.out.println(a.getFields());
2) System.out.println(a.name);
3) System.out.println((Base) a.getFields());
4) System.out.println( ((Agg) a).getFields());
Ans: 4. 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.
Ques: The following code resides in the source?
class StringTest
{public static void main( String [] agrs) {
String a,b;
StringBuffer c,d;
c = new StringBuffer("Hello");
a = new String("Hello");
b = a;
d = c;
if ( <<<operator>>> ) { }
}} //class
Which of the following statement return true for the
<<>> line in StringTest.class?
1) b.equals(a)
2) b==a
3) d==c
4) d.equals(c)
Ans: 1,2,3,4. This is a tricky question. Both 1 and 4
answers are comparing the content of string a,b and stringbuffer d,c but both 2 and 3
answers are comparing the object reference number not the content "Hello".For
example if we change the code to this:
a = new String("Hello");
b = new String("Hello");
Then the b==a wouldn't give true because the reference numbers are different.
Ques: We have the following organization of classes.
class Parent { }
class DerivedOne extends Parent { }
class DerivedTwo extends Parent { }
Which of the following statements is correct for the following expression.
Parent p = new Parent();
DerivedOne d1 = new DerivedOne();
DerivedTwo d2 = new DerivedTwo();
d1 = (DerivedOne)d2;
A) llegal both compile and runtime,
B) Legal at compile time, but fails at runtime,
C) Legal at compile and runtime
Ans: A - Illegal both compile and runtime, you cannot assign an object to a sibling reference, even with casting.
Ques: Choose the correct statement about gridbag layout:
A. The weightx & weighty should have values
between 0.0 & 1.0
B. If you specify the fill field is BOTH, there is no meaning to set anchor field
C. If you specify anchor field there is no meaning to set fill field is BOTH
Ans: A B C
Ques: Choose the correct one about thread:
A. The threads from one class ends at the same time.
B. when JVM exists the main method, it will stop only after all the threads are stopped.
C. if there are multiple threads, reading or writing of data of class is inconsitent.
D. programmer has to write a special program for garbagecollection in multiple threads
Ans: B C
Ques: All the methods in Listener Interfaces should be?
A. private
B. public
C. protected
D. undefined (friendly)
E. static
F. final
Ans: B - The answer is 'B' because in the API documentation all the Listener Interfaces have "public void method()".
Ques: Which of the following statements is valid?
A. The JVM runs till the main method exits, even if
there are other user threads running.
B. An InterruptedException occurs when the sleep() method is called on a thread.
C. A thread can be suspended for an indefinite duration of time.
D. A thread can be made in Java only by subclassing the Thread class.
E. The synchronize keyword can be used only in a method that is part of a class that is
derived from Thread
Ans: C
Ques: Which statements are true about listeners?
A. The return value from a listener is of boolean
type.
B. Most components allow multiple listeners to be added.
C. A copy of the original event is passed into a listener method.
D. If multiple listeners are added to a single component, they all must all be friends to
each other.
E. If the multiple listeners are added to a single component, the order [in which
listeners are called is guaranteed].
Ans: B C
Ques: What might cause the current thread to stop executing.
A. An InterruptedException is thrown.
B. The thread executes a wait() call.
C. The thread constructs a new Thread.
D. A thread of higher priority becomes ready.
E. The thread executes a waitforID() call on a MediaTracker.
Ans: A B D E
Ques: What should you use to position a Button within an application frame so that the width of the Button is affected by the Frame size but the height is not affected.
A. FlowLayout
B. GridLayout
C. Center area of a BorderLayout
D. East or West of a BorderLayout
E. North or South of a BorderLayout
Ans: E
Ques: Given a TextArea using a proportional pitch
font and constructed like this:
TextField t = new TextArea("12345", 5, 5);
Which statement is true?
A. The displayed width shows exactly five characters
on each line unless otherwise constrained.
B. The displayed height is five lines unless otherwise constrained.
C. The maximum number of characters in a line will be five.
D. The user will be able to edit the character string.
E. The displayed string can use multiple fonts.
Ans: B D
Ques: Given a TextField that is constructed like
this:
TextField t = new TextField(30);
Which statement is true?
A. The displayed width is 30 columns.
B. The displayed string can use multiple fonts.
C. The user will be able to edit the character string.
D. The displayed line will show exactly thirty characters.
E. The maximum number of characters in a line will be thirty.
Ans: A C
Ques: What does it mean when the handleEvent() returns the true boolean?
A. The event will be handled by the component.
B. The action() method will handle the event.
C. The event will be handled by the super.handleEvent().
D. Do nothing.
Ans: A
Ques: Which variables can an inner class access from the class which encapsulates it?
A. All static variables
B. All final variables
C. All instance variables
D. Only final instance variables
E. Only final static variables
Ans: A B C
Ques: Which methods may cause a thread to stop executing?
A. sleep();
B. stop();
C. yield();
D. wait();
E. notify();
F. notifyAll()
G. synchronized()
Ans: A B C D
Ques: Which of the following, are valid return types, for listener methods:
A. boolean
B. the type of event handled
C. void
D. Component
Ans: C
Ques: Which of the following illustrates the correct way to pass a parameter into an applet:
A. <applet code=Test.class age=33 width=100
height=100>
B. <param name=age value=33>
C. <applet code=Test.class name=age value=33 width=100 height=100>
D. <applet Test 33>
Ans: B
Ques: What is the result of compiling and executing the following Java class:
public class ThreadTest extends Thread {
public void run() {
System.out.println("In run");
suspend();
resume();
System.out.println("Leaving run");
}
public static void main(String args []) {
(new ThreadTest()).start();
}
}
A. Compilation will fail in the method main.
B. Compilation will fail in the method run.
C. A warning will be generated for method run.
D. The string "In run" will be printed to standard out.
E. Both strings will be printed to standard out.
F. Nothing will happen.
Ans: D
Ques: Consider the following tags:
1. CODEBASE
2. ALT
3. NAME
4. CLASS
5. JAVAC
6. HORIZONTALSPACE
7. VERTICALSPACE
8. WIDTH
9. PARAM
10. JAR
Which of the above are tags that can be used within the APPLET tag?
A. line 1, 2, 3
B. line 2, 5, 6, 7
C. line 3, 4, 5
D. line 8, 9, 10
E. line 8, 9
Ans: A E
Ques: Select all right answers.
a) class Animal { abstract void growl(); }
b) abstract Animal {abstract void growl();}
c) class abstract Animal {abstract void growl();}
d) abstract class Animal {abstract void growl();}
e) abstract class Animal {abstract void growl() {System.out.println("growl");}}
Ans: d. An abstract class is defined using the
keyword abstract in front of the class keyword
and almost always defines at least one abstract method. An abstract class does not have to
define an abstract method. If there are no abstract methods in an abstract class, then any
subclasses of the abstract class can be instantiated (as long as they are not, in turn,
defined
using the abstract keyword).
Ques: What modes are legal for creating a new RandomAccessFile object?
Select all valid answers.
a) "w"
b) "r"
c) "x"
d) "rw"
e) "xrw"
Ans: b, d. Only "r" and "rw" are legal modes for a RandomAccessFile.
Ques: Which assignments are legal? Select all valid
answers.
a) long test = 012;
b) float f = -412;
c) int other = (int)true;
d) double d = 0x12345678;
e) short s = 10;
Ans:: a, b, d, and e. The other tries to cast a boolean to an int, which is illegal.
Ques: Which label name(s) are illegal? Select all valid answers.
- here:
- _there:
- this:
- that:
- 2to1odds:
Ans: c, e. this is a reserved word, so it cannot be used as an identifier (such as a label). 2to1odds starts with a number, so it is also invalid as an identifier.
Ques: If you run the following code on a on a PC from the directory c:\source: import java.io.*;
class Path {
public static void main(String[] args) throws Exception {
File file = new File("Ran.test");
System.out.println(file.getAbsolutePath());
System.out.println(file.getPath());
}}
what do you expect the output to be? Select the one right answer.
- Ran.test, Ran.test
- source\Ran.test, Ran.test
- c:\source\Ran.test, null
- c:\source, Ran.test
- null, Ran.test
Ans: c. The absolute path includes the drive name and the top-level directories, as well asthe file name itself. The getPath() returns the path name as specified in the File constructor else returns null.
Ques: When you invoke repaint() for a Component, the AWT package calls which Component method?
- repaint()
- update()
- paint()
- draw()
- show()
Ans: b. The AWT invokes update() for the Component, which in turn invokes paint() in its default behavior.
Ques: The setForeground() and setBackground() methods are defined in class: Select the one right answer.
- Graphics
- Container
- Component
- Object
- Applet
Ans: C
Ques: Which operators are overloaded for String objects? Select all valid answers.
- -
- +=
- >>
- &
- none of these
Ans: b. Only + and += are overloaded for String objects.
Ques: Imagine there are two exception classes called Exception1 and Exception2 that descend from the Exception class. Given these two class definitions:
class First {
void test() throws Exception1, Exception2 { . . . }
}
class Second extends First {
void test() { . . . }
}
Create a class called Third that extends Second and defines a test() method. What exceptions can Thirds test() method throw? Select all valid answers.
- Exception1
- Exception2
- no checked exceptions
- any exceptions declared in the throws clause of the Thirds test() method.
Ans: c. A method in a subclass cannot add new exception types that it might throw. Since its superclass, Second, does not define any exceptions in its test() method, Third cant either.
Ques: What is the result of executing the following code:
class Test {
public static void main(String[] args) {
Test t = new Test();
t.test(1.0, 2L, 3);
}
void test(double a, double b, short c) {
System.out.println("1");
}
void test(float a, byte b, byte c) {
System.out.println("2");
}
void test(double a, double b, double c) {
System.out.println("3");
}
void test(int a, long b, int c) {
System.out.println("4");
}
void test(long a, long b, long c) {
System.out.println("5");
}
}
Select the one right answer.
- 1
- 2
- 3
- 4
- 5
Ans: c. The method with all double parameters is actually the only version of test() that the Java Virtual Machine can legally coerce the numbers to. The reason the other versions of test() are not invoked is that at least one of the parameters would have to be automatically coerced from a type with greater accuracy to a type with less accuracy, which is illegal.
Ques: Given this code snippet:
double a = 14.9;
double b = method(a);
System.out.println(b);
If this snippet displays 15.0 in the standard output, what Math method(s) could method() have invoke? Select the one right answer.
- ceil() and round()
- floor() and round()
- ceil() only
- floor() only
- round() only
Ans: c. Only ceil(). Round() will produce 15 from 14.9 not 15.0. The floor() method yields 14.
Ques: What methods does Java define in the Math class specifically for trigonometric calculations? Select all valid answers.
- cos()
- asin()
- tan()
- sin()
- angle()
Ans: a, b, c, d. The methods Java defines for trig operations include sin(), asin(), cos(), and tan().
Ques: At the end of these two lines of code: String s = "hypertext"; String t = s.substring(2, 5); What does the object reference t contain? Select the one right answer.
- "yper"
- "ype"
- "pert"
- "per"
- "perte"
Ans: d. The method substring() starts at the first index, inclusive, with 0 being the first character), and ends at the end index - 1 (that is, exclusive of the end index).
Ques: Which expressions are illegal? Select all valid answers.
- (true & true)
- (4 & 5)
- (int myInt = 0 > 3)
- float myFloat = 40.0;
- boolean b = (boolean)99;
Ans: d, c, e. You cannot assign an integer to a booleannot even with casting. Also, the default type for a floating-point literal is double, and you cannot assign a double to a float without casting.
Ques: Given following varibales, state what happens for each operation:
Declaration/Assigment |
Javac Errors |
Remarks |
|
char c1 = 2 + '2'; |
No Errors. Now c1 equals 4 !! | ||
char c1 = 2 + 'a'; |
No Errors. Now c1 equals c !! | ||
| char c1 = 2 + cc; | Incompatible
type for declaration. Explicit cast needed to convert int to char. char c1 = 2 + cc; |
||
| short s1 = s + bb; | Hello.java:15:
Incompatible type for declaration. Explicit cast needed to convert int to short. short s1 = s + bb; |
||
| short s1 = '20'; | Hello.java:15:
Invalid character constant. short s1 = '20'; |
||
| short s1 = '2'; | Hello.java:15:
Incompatible type for declaration. Explicit cast needed to convert char to short. short s1 = '2'; |
||
| short s1 = (short) '20'; | Hello.java:15:
Invalid character constant. short s1 = (short)'20'; |
||
| short s1 = 20 + '2'; | No Errors. S1 now equals 70 (Character 2 is decimal 50) | ||
| Short s1 = 20 + cc | Hello.java:15:
Incompatible type for declaration. Explicit cast needed to convert int to short. short s1 = 20 + cc; |
||
| char c1 = bb; | Hello.java:16:
Incompatible type for declaration. Explicit cast needed to convert byte to char. char c1 = bb; |
||
| char c1 = bb + 1; | Hello.java:16:
Incompatible type for declaration. Explicit cast needed to convert int to char. char c1 = bb + 1; |
||
public class
Hello {int [] count; public static void main(String a[]) {
} // end Hello |
No Errors: The
output is null [I@703f2530 ß memory address Note that the class variables are always initialized to defallt values but the automatic variables are never initialized. However in case of arrays they are always initialized, even if they are automatic, provided they are contructed using new operator (just declaring an array in not enough) |
||
| public class
Hello { public static void main(String args[]) { int [] count; System.out.println(count); count = new int[2]; System.out.println(count);}} |
C:\Abhishek\java>javac
Hello.java Hello.java:12: Variable count may not have been initialized. System.out.println(count); ^ 1 error |
||
Ques: Which of the following correctly illustrate how an InputStreamReadercan be created:
- new InputStreamReader(new FileInputStream("data"));
- new InputStreamReader(new FileReader("data"));
- new InputStreamReader(new BufferedReader("data"));
- new InputStreamReader(System.in);
Ans: a, d. InputStreamReader is a bridge between byte streams and character streams. Hence its input must always be a byte stream source. FileReader is a combination of InputStreamReader and FileInputStream, so it cannot be used.
Ques: What will happen if you run the following code:
}}
- Runtime exception
- Test is printed
- Nothing is printed
- Compile failure
Ans: d. The following message is produced:
Test.java:3: Undefined variable: this this.print();
Ques: Which lines will give compilation error:
A. public class Test {
B. public static void main(String args[]) {
C. StringBuffer sb = new StringBuffer("abc");
D. String s = new String("abc");
E. sb.append("def");
F. sb.append('g');
G. s.append("def");
H. sb.insert(1, "ZZZ");
I. s.concat("ZZZ");
J. s.trim();
}
Ans: G. s.append("def") will give
compilation error. Rest all are okay !!
Test.java:7: Method append(java.lang.String) not found in class java.lang.String.
s.append("def");
Ques: What will happen if you compile/run this code?
1: public class Q1 extends Thread
2: {
3: public void run()
4: {
5: System.out.println("Before start method");
6: this.stop();
7: System.out.println("After stop method");
8: }
9:
10: public static void main(String[] args)
11: {
12: Q1 a = new Q1();
13: a.start();
14: }
15: }
A) Compilation error at line 7.
B) Runtime exception at line 7.
C) Prints "Before start method" and "After stop method".
D) Prints "Before start method" only.
Ans: D
Ques: What will happen if you compile/run the following code?
1: class Test
2: {
3: static void show()
4: {
5: System.out.println("Show method in Test class");
6: }
7:}
8:
9: public class Q2 extends Test
10: {
11: static void show()
12: {
13: System.out.println("Show method in Q2 class");
14: }
15: public static void main(String[] args)
16: {
17: Test t = new Test();
18: t.show();
19: Q2 q = new Q2();
20: q.show();
21:
22: t = q;
23: t.show();
24:
25: q = t;
26: q.show();
27: }
28: }
A) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Q2 class"
"Show method in Q2 class"
B) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Test class"
"Show method in Test class"
C) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Test class"
"Show method in Q2 class"
D) Compilation error.
Ans: D. However, if line 25 is commented, then the answer would be C. Thats because the show() method is static and so the show() method will be resolved at compile time. And if the show() method is made an instance method the answer would be A because now the call will be resolved during runtime based on the object type.
Ques: The following code will give
1: class Test
2: {
3: void show()
4: {
5: System.out.println("non-static method in Test");
6: }
7: }
8: public class Q3 extends Test
9: {
10: static void show()
11: {
12: System.out.println("Overridden non-static method in Q3");
13: }
14:
15: public static void main(String[] args)
16: {
17: Q3 a = new Q3();
18: }
19: }
A) Compilation error at line 3.
B) Compilation error at line 10.
C) No compilation error, but runtime exception at line 3.
D) No compilation error, but runtime exception at line 10.
Ans: B. Cannot override an instance method to be static.
Ques: The following code will give
1: class Test
2: {
3: static void show()
4: {
5: System.out.println("Static method in Test");
6: }
7: }
8: public class Q4 extends Test
9: {
10: void show()
11: {
12: System.out.println("Overridden static method in Q4");
13: }
14: public static void main(String[] args)
15: {
16: }
17: }
A) Compilation error at line 3.
B) Compilation error at line 10.
C) No compilation error, but runtime exception at line 3.
D) No compilation error, but runtime exception at line 10.
Ans: B. Cannot override a static method to be an instance method.
Ques: The following code will print
1: int i = 1;
2: i <<= 31;
3: i >>= 31;
4: i >>= 1;
5:
6: int j = 1;
7: j <<= 31;
8: j >>= 31;
9:
10: System.out.println("i = " +i );
11: System.out.println("j = " +j);
A) i = 1 j = 1
B) i = -1 j = 1
C) i = 1 j = -1
D) i = -1 j = -1
Ans: D
Ques: The following code will print
1: Double a = new Double(Double.NaN);
2: Double b = new Double(Double.NaN);
3:
4: if( Double.NaN == Double.NaN )
5: System.out.println("True");
6: else
7: System.out.println("False");
8:
9: if( a.equals(b) )
10: System.out.println("True");
11: else
12: System.out.println("False");
A) True True
B) True False
C) False True
D) False False
Ans: C
Ques: The following code will print
1: if( new Boolean("true") == new
Boolean("true"))
2: System.out.println("True");
3: else
4: System.out.println("False");
A) Compilation error.
B) No compilation error, but runtime exception.
C) Prints "True".
D) Prints "False".
Ans: D
Ques: The following code will print
1: Byte b1 = new Byte("127");
2:
3: if(b1.toString() == b1.toString())
4: System.out.println("True");
5: else
6: System.out.println("False");
A) Compilation error, toString() is not avialable for
Byte.
B) Prints "True".
C) Prints "False".
Ans: C
Ques: What will happen if you compile/run this code?
1: public class Q10
2: {
3: public static void main(String[] args)
4: {
5: int i = 10;
6: int j = 10;
7: boolean b = false;
8:
9: if( b = i == j)
10: System.out.println("True");
11: else
12: System.out.println("False");
13: }
14: }
A) Compilation error at line 9 .
B) Runtime error exception at line 9.
C) Prints "True".
D) Prints "False".
Ans: C
Ques: What is the output of the following code?
1: class Test
2: {
3: Test(int i)
4: {
5: System.out.println("Test(" +i +")");
6: }
7: }
8:
9: public class Q12
10: {
11: static Test t1 = new Test(1);
12:
13: Test t2 = new Test(2);
14:
15: static Test t3 = new Test(3);
16:
17: public static void main(String[] args)
18: {
19: Q12 Q = new Q12();
20: }
21: }
A) Test(1) Test(2) Test(3)
B) Test(3) Test(2) Test(1)
C) Test(2) Test(1) Test(3)
D) Test(1) Test(3) Test(2)
Ans: D No matter where they declared, static variables will be intitialized before non-static variables.
Ques: What is the output of the following code?
1: int i = 45678;
2: int j = ~i;
3:
4: System.out.println(j);
A) Compilation error at line 2. ~ operator applicable
to boolean values only.
B) Prints 45677.
C) Prints -45677.
D) Prints -45679.
Ans: D. Java allows you to use ~ operator for integer type variables. The simple way to calculate is ~i = (- i) - 1.
In the following applet, how many Buttons will be displayed?
1: import java.applet.*;
2: import java.awt.*;
3:
4: public class Q16 extends Applet
5: {
6: Button okButton = new Button("Ok");
7:
8: public void init()
9: {
10: add(okButton);
11: add(okButton);
12: add(okButton);
13: add(okButton);
14:
15: add(new Button("Cancel"));
16: add(new Button("Cancel"));
17: add(new Button("Cancel"));
18: add(new Button("Cancel"));
19:
20: setSize(300,300);
21: }
22: }
A) 1 Button with label "Ok" and 1 Button
with label "Cancel" .
B) 1 Button with label "Ok" and 4 Buttons with label "Cancel" .
C) 4 Buttons with label "Ok" and 1 Button with label "Cancel" .
D) 4 Buttons with label "Ok" and 4 Buttons with label "Cancel" .
Ans: B
Ques: The following code will print
1: import java.applet.*;
2: import java.awt.*;
3:
4: public class Q20 extends Applet
5: {
6: Button okButton = new Button("Ok");
7:
8: public void init()
9: {
10: setLayout(new BorderLayout());
11:
12: add("South", okButton);
13: add("North", okButton);
14: add("East", okButton);
15: add("West", okButton);
16: add("Center", okButon);
17:
18: setSize(300,300);
19: }
20: }
The above Applet will display
A) Five Buttons with label "Ok" at Top, Bottom, Right, Left and Center of the
Applet.
B) Only one Button with label "Ok" at the Top of the Applet.
C) Only one Button with label "Ok" at the Bottom of the applet.
D) Only one Button with label "Ok" at the Center of the Applet.
Ans: D
Ques: Which of the following are valid array declarations/definitions?
1: int iArray1[10];
2: int iArray2[];
3: int iArray3[] = new int[10];
4: int iArray4[10] = new int[10];
5: int []iArray5 = new int[10];
6: int iArray6[] = new int[];
7: int iArray7[] = null;
A) 1.
B) 2.
C) 3.
D) 4.
E) 5.
F) 6.
G) 7.
Ans: B,C,E and G. You can't specify the array dimension in type specification(left hand side),so A and D are invalid. In line 6 the array dimension is missing(right hand side) so F is invalid. You can intialize an array with null. so G is valid.
Ques: What is the output for the following lines of code?
1: System.out.println(" " +2 + 3);
2: System.out.println(2 + 3);
3: System.out.println(2 + 3 +"");
4: System.out.println(2 + "" +3);
A) Compilation error at line 3
B) Prints 23, 5, 5 and 23.
C) Prints 5, 5, 5 and 23.
D) Prints 23, 5, 23 and 23.
Ans: B
Ques: The following declaration(as a member variable) is legal.
static final transient int maxElements = 100;
A) True.
B) False.
Ans: A
Ques: What will happen if you invoke the following method?
1: public void check()
2: {
3: System.out.println(Math.min(-0.0,+0.0));
4: System.out.println(Math.max(-0.0,+0.0));
5: System.out.println(Math.min(-0.0,+0.0) == Math.max(0.0,+0.0));
6: }
A) prints -0.0, +0.0 and false.
B) prints -0.0, +0.0 and true.
C) prints 0.0, 0.0 and false.
D) prints 0.0, 0.0 and true.
Ans: C
Ques: When executed the following line of code will print
System.out.println(-1 * Double.NEGATIVE_INFINITY);
A) -Infinity
B) Infinity
C) NaN
D) -NaN
Ans: B
Ques: Which of the following statements are true?
a) An abstract method cannot be final
b) An abstract method cannot be static
c) An abstract method cannot be private
d) An abstract method must be specified inside an abstract class only
e) An abstract method cannot throw any exceptions
Select all valid answers.
Ans: A B C D. An abstract method cannot be static since static methods cannot be overriden
Ques: Abstract class cannot have final methods. True or False ?
a) True
b) False
Ans: B. But Abstract class cannot have final abstract methods!!
Ques: Abstract method cannot be static. True or False ?
a) True
b) False
Ans: A
Ques: What tags are mandatory when creating HTML to display an applet. Select most appropriate answer.
a) name, height, width
b) code, name
c) codebase, height, width
d) code, height, width
e) None of the above
Ans: D
Ques: Which of the following valid statements. Select all valid answers.
a) an array extends Object
b) an array extends Cloneable
c) an array implements Cloneable
d) an array extends primitive types like int, char, byte
e) None
Ans: A C
Ques: What will be the output when you compile and execute the following program.
public class Base {
void test() {
String aStr = "ONE";
String bStr = aStr;
String cStr = new String (aStr);
if(aStr == bStr)
System.out.println("aStr == bStr");
if(aStr == cStr)
System.out.println("aStr == cStr");
if(aStr.equals(cStr))
System.out.println("aStr.equals(cStr)");
if(aStr == aStr.toUpperCase())
System.out.println("aStr == aStr.toUppercase()");
if("One".equalsIgnoreCase(aStr))
System.out.println("One.equalsIgnoreCase(aStr)");
if("ONE" == aStr)
System.out.println("ONE == aStr");
}
static public void main(String[] a) {
new Base().test();
}
}
Select most appropriate answer.
a)
aStr == bStr
aStr.equals(cStr)
aStr == aStr.toUppercase()
One.equalsIgnoreCase(aStr)
ONE == aStr
b)
aStr == bStr
aStr == cStr
aStr.equals(cStr)
aStr == aStr.toUppercase()
One.equalsIgnoreCase(aStr)
ONE == aStr
c)
aStr.equals(cStr)
d)
aStr.equals(cStr)
One.equalsIgnoreCase(aStr)
Ans: A
Ques: What will be the output when you compile and execute the following program.
class Base
{
static void test() {
System.out.println("Base.test()");
}
}
public class Child extends Base {
static void test() {
System.out.println("Child.test()");
}
static public void main(String[] a) {
Child anObj = new Child();
anObj.test();
Base baseObj = (Base)anObj;
baseObj.test();
}
}
Select most appropriate answer.
a) Child.test()
Base.test()
b) Child.test()
Child.test()
c) Base.test()
Base.test()
d) Compilation error. Cannot override a static method
e) Runtime error. Cannot override a static method
Ans: A. Thats because both the methods are static methods. If the test() is madean instance method in both the classes then the answer would be B !!
Ques: A label for the continue statement
a) must be before a for, do or while loop (other than
white space(s) and comments)
b) must be before an if, else, for, do or while statements (other than white space(s) and
comments)
c) should not be before another label
d) must be before an opening brace like '{'
e) None of the above
Select all valid answers
Ans: A
When you compile and execute the following program which lines will give compilation and/or runtime errors.
01:public class Base{
02: private void test() {
03:
04: int i = 3;
05: int a[] = { 0, 1 };
06: Integer b[] = new Integer[i*i];
07: Long c[] = { new Long(1L) , new Long(2L) };
08: int d[] = new int[] { 10, 20 };
09: int e[] = new int[2] { 10, 20 };
10: Integer f[] = new Integer[i];
11:
12:}
13:
14: static public void main(String[] a) {
15: new Base().test();
16: }
17:
18:}
a) Invalid array initialization at line 05
b) Invalid array size at line 06. A local variable cannot be used as array size
c) Invalid array initialization at line 07
d) Invalid array initialization at line 08. Cannot new and initialize an array at same
time
e) Error at line 09. Cannot specify array size and initialize an array at same time
f) Invalid array size at line 10. A local variable cannot be used as array size
Ans: E
Ques: What will be the output when you compile and execute the following program.
class Base
{
static void test() {
System.out.println("Base.test()");
}
}
public class Child extends Base {
static void test() {
System.out.println("Child.test()");
super.test();
}
static public void main(String[] a) {
test()
}
}
Select most appropriate answer.
a) Child.test()
Base.test()
b) Child.test()
Child.test()
c) Base.test()
Base.test()
d) Compilation error. Cannot call super from a static method
e) Runtime error. Cannot call super from a static method
Ans: D
Ques: What does "finalize" method do?
Ans: B
Ques: Can I have some problems in a multi-threaded context if I declare only local variables in a method?
Ans: C
Ques: To be a Bean, a Java class must:
A. respect at least naming standards
B. be multi-threaded safe
C. implement the "Serializable" interface
D. nothing. Every Java class in a separate file is a valid bean
Ans: D
Ques: Java object implementing Serializable and
containing handles to not-serializable Objects
A. is serializable
B. is serializable in shallow-copy
C. is not serializable
Ans: C
Ques: Let's pass a String object to a method, which
is supposed to modify its value:
A. I'm absolutely sure the object will have the same value at method return
B. I have to investigate if the method has overwritten the value
C. I'm not worried because the method creates a local copy of the object, so my object is
safe
D. The method creates a local copy of the handle, not of the object, so this is a typical
handle aliasing. I must worry!
Ans: A. Because String is immutable, so B and D are wrong. For an mutable object (a normal
one) they would be right.
Ques: It's possible to create a type-conscious Vector
class:
A. no
B. yes, inheriting from Vector and overriding addElement() and other important methods
C. yes, using the Delegation pattern, with no inheritance, mantaining an handle to a
Vector object and implementing addElement() and other important method in a way they call
local handle ones.
Ans: C. answer B seems right too, but all important Vector methods are final for
efficiency reasons