Java Questions
Java Questions
A1 000
A2 ArrayIndexoutOfBoundsException
A3 NullPointerException
A4 null null null
A1 "Called"
A2 Compiler
A3 Runtime
A4 Nothing
A1 "Called"
A2 Compiler
A3 Runtime Exception
A4 Nothing is printed in screen
A1 "Constructor1"
A2 "Constructor2"
A3 "Constructor1""Constructor2"
A4 Compiler Errror
A1 4
A2 44
A3 Compiler Error
A4 Compiles and Runs without error
A1 HI
A2 hai
A3 Hai Hi
A4 Hi Hai
A1 public Test8(){}
A2 private void Test8(){}
A3 protected Test8(int k){}
A4 Test8(){}
A1 abstract method(){}
A2 abstrct void method(){}
A3 final void method(){}
A4 int method(){}
A1 class Test10
A2 public class Test10
A3 final class Test10
A4 abstract final class Test10
A1 method
A2 variable
A3 class
A4 constructor
Q14)Which of the following modifiers can be used with top class declaration?
A1 static
A2 privatr
A3 public
A4 final
A5 abstract
A1 Instance Static
A2 Static Instance
A3 Static
A4 Static Instance Constructor
class Sup{
public Sup(String str){
System.out.println("Super class");
}
}
A1 Super class,SubClass
A2 Super class
A3 Sub class
A4 Compiler Error
A1 Main Method1
A2 Main Method1 Main Method2
A3 Main Method2
A4 Runtime Exception
A1 Sample Program
A2 Compiler Error
A3 Runtime Exception
A4 None
class Sup1{
public Sup1(){
System.out.println("Hai");
}
private Sup1(String str){
System.out.println(str);
}
}
A1 Hai,Hi,Hi
A2 Hai,Hi
A3 Hi,Hi
A4 Compiler Error
A1 String
A2 Integer
A3 StringBuffer
A4 Boolean
A1 float f = 1;
A2 float f = 1.2f;
A3 float f = 1.2;
A4 float f = (float)1.2;
String s2 = "hi";
System.out.println(s1 ==s2);
System.out.println(s1.equals(s2));
A1 false true
A2 true false
A3 true true
A4 None of the above.
Q25)Integer i = new Integer(0);
A1 true false
A2 false true
A3 true true
A4 Compiler error
1) A1 is correct
Local Array variables are initialized to their default values.
4) A1) "Called"
Static methods canbe called only by referance.Because its not binded with objects.So, in this case
"null" value doesn't make sense."method" is called without any problem.
5) A2)"Constructor2"
Constructors cannot have return types. If its declared with return types then it is consider as
methods. So, output wull be "Constructor2".
6) A3)Compiler Error
7) A3)Hai Hi
8) A1)public Test8(){}
A3)protected Test8(int k){}
11) b)variable
16) c)Static
21) A1)String
A4)String Buffer
25)A4)Compiler error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import java.util.*;
public class Test1{
public static void main(String a[]){
Set s = new TreeSet();
s.add(new Person(20));
s.add(new Person(10));
System.out.println(s);
}
}
class Person{
Person(int i){}
}
What is the output?
A1 10 20
A2 ClassCastException
A3 Compiler Error
A4 Compiler Error
import java.util.*;
public class Test2{
public static void main(String a[]){
Map s = new Hashtable();
s.put(null,null);
Q2
System.out.println(s);
}
}
What is the output?
A1 [null = null]
A2 NullPointerException
A3 null
A4 []
import java.util.*;
public class Test3{
public static void main(String a[]){
Map s = new WeakHashMap(10);
s.put(null,null);
Q3
System.out.println(s);
}
}
import java.util.*;
public class Test4{
public static void main(String a[]){
Map s = new LinkedHashMap();
s.put("1","one");
Q4 s.put("3","three");
s.put("2","two");
System.out.println(s);
}
}
What is the output?
A1 [1=one,3=three,2=two]
A2 NullPointerException
A3 [1=one,2=two,3=three]
A4 []
import java.util.*;
public class Test5{
public static void main(String a[]){
Map s = new HashMap();
s.put("1","one");
Q5 s.put("3","three");
s.put("2","two");
System.out.println(s);
}
}
What is the output?
A1 [1=one,3=three,2=two]
A2 [3=three,2=two,1=one]
A3 cannot predict the order
A4 []
A1 Double Double Double Double Double
A2 Float Float Float Float Float
A3 Double Float Float Double Float
A4 Double Float Float Double Double
Q8 c = b; // 1
s = b; // 2
i = b; //3
s = c * b; //4
}
}
Which of the following are correct?
A1 Error at mark 1
A2 Error at mark 2
A3 Error at mark 3
A4 Error at mark 4
public class Test9{
public static void main(String a[]){
final byte b = 1;
char c = 2;
short s = 3;
int i = 4;
Q9 c = b; // 1
s = b; // 2
i = b; //3
s = c * b; //4
}
}
Which of the following are correct?
A1 Error at mark 1
A2 Error at mark 2
A3 Error at mark 3
A4 Error at mark 4
What is output?
A1 false true
A2 true false
A3 true true
A4 Compiler Error
import java.util.*;
public class Test17{
public static void main(String a[]){
Map m = new Hashtable(10,0.75f);
Q17 System.out.println(m.size());
}
}
What is output?
A1
A2 10
A3 7
A4 cOMPILER eRROR
A1 8 10
A2 10 10
A3 18 10
A4 18 18
Answers
1 ClassCastException
2 NullPointerException
3 [null = null]
4 [1=one,3=three,2=two]
5 cannot predict the order.
6 Double Float Float Double Float
7 Int Int Byte Byte
Error at mark 1
8
Error at mark 4
9 Error at mark 4
10 Sun
11 false true false
12 Compiler Error
13 Compiler Error
14 Local New Instance
15 String Buffer Added
16 String Buffer
17 0
18 11
19 16
Vector
20
HashTable
21 false false true
22 SunMicrosystems unM Systems
23 StringIndexOutOfBoundsException
24 valueOf
25 18 10
Mock Exam - 3
1
A1 2
A2 3
A3 4
A4 Compiler error
import java.io.IOException;
public class Test5{
public static void main(String args[]){
try{
throw new IOException();
}
catch(Exception e){
Q5 System.out.println("Excepion");
}
catch(IOException e){
System.out.println("IOExcepion");
}
}
}
What will be the output?
A1 Exception
A2 IOException
A3 Exception IOException
A4 Compilers error
import java.io.IOException;
public class Test12 extends A{
public void method() throws Exception{
System.out.println("Subclass");
}
public static void main(String args[]) throws Exception{
A a = new A();
a.method();
a = new Test12();
Q12
a.method();
}
}
class A{
public void method() throws IOException{
System.out.println("Superclass");
}
}
What will be the output?
A1 Subclass Superclass
A2 Runtimxception
A3 Superclass Superclass
A4 Compiler Error
Mock Exam - 4
Q3 class Test{}
public class Test3{
static void method(Object obj){
System.out.println("StringBuffer");
}
static void method(String str){
System.out.println("String");
}
static void method(Test t){
System.out.println("Test");
}
public static void main(String args[]){
method(null);
}
}
What will be the output?
A1 String
A2 Object
A3 Test
A4 Compiler Error
{
k = k * 2;
}
Q9 public static void main(String args[]){
System.out.println(k);
}
}
What will be the output?
A1 1
A2 2
A3 4
A4 Compiler Error
Q1
Wh
ich
of
the
foll
owi
ng
are
the
cor
rec
t
for
m
of
doc
um
ent
ati
on
co
m
me
nts
?
A1 //some text here
A2 /*some text here*/
A3 /**some text here*/
A4 all the above
which of the following is the correct way to define a class that will
Q4
be in the default package
package default;
A1 import java.util.*;
import java.util.*;
A2
package default;
A3 import java.util.*;
A4 all the above
System.out.println(args[1]);
}
Q10
Mock 6
A. ASCII code
B. Binary code
C. Unicode
D. ANSI code
A. 32 bytes
B. 16 bits
C. 32 bits
D. 16 bytes
A. true
B. false
C. 0
D. 1
A. 0
B. '\u0000'
C. null
A. True
B. False
A. temp
B. BIGint
C. 25_length
D. !length
A. byte
B. int
C. double
D. short
E. long
F. float
A. true
B. false
A. 320
B. 0
C. 645
D. 64
A. 1.75
B. 0
C. 1
D. 2
C. Both A and B
D. None of the above
A. Multiplication: *
B. Division: /
C. Modulo: %
D. Addition: +
E. Subtraction: -
14. Please select operators which perform bit shifts of the binary
representation of the integral types
A. <<
B. >>
C. >>>
D. ~
E. &
F. ^
G. |
A. A private method
B. A protected method
C. A public method
A. A private method
B. A protected method
C. A public method
A. A variable
B. A method
A. A variable
B. A method
C. A class
D. A constructor
A. protected
B. private
C. public
D. static
A. True
B. False
A. The do loop
A. A char value
B. An int value
C. A String value
D. It is never provided
C. Both A and B
A. java.util.List
B. java.util.Set
C. java.util.Map
A. java.awt.FlowLayout
B. java.awt.BorderLayout
C. java.awt.GridBagLayout
C. Both A and B
A. boolean javaExam=true;
B. boolean javaExam=True;
C. boolean javaExam=1;
A. Integral types
B. Float types
A. interfaces
B. Arrays
C. Classes
A. s == t
B. x!=y
C. x==s
D. s!=t
A. 0
B. 1
C. 5
D. 10
A. start()
B. sleep(long l)
C. run()
D. yield()
52. Select true statement(s) about an inner class declared inside
a method, also known as local inner class
53. How can you prevent class JavaExam from being extended?
. float
long
String
. include
ifdef
sizeof
goto
59. Which of the following statements are NOT true about Java
garbage collection Thread?
. static
protected
final
transient
. reference
null
int
. True
False
. True
False
. True
False
True
False
True
False
True
False
size()
capacity()
java.lang.ClassNotFoundException
java.lang.ClassCastException
java.awt.AWTException
java.lang.String
java.lang.StringBuffer
java.util.Vector
java.lang.Integer
java.util.Hashtable
java.util.Vector
java.util.LinkedList
java.util.HashMap
77. Which of the following classes can store null value for a key?
java.util.Hashtable
java.util.HashMap
java.util.Properties
True
False
True
False
True
False
java.util.Vector
java.util.Hashtable
java.util.HashMap
java.util.ArrayList
java.util.Dictionary
java.util.Map
java.util.HashMap
java.util.Hashmap
Answers:
1. B
2. C
3. C
4. B
5. B
6. B
7. C and D
8. C and F
9. A
11. C
12. A
14. A, B, and C
15. B and C
16. A and B
17. A and B
18. A and D
19. D
21. A
22. A and B
23. A and B
24. C
25. A and B
26. A
27. A
28. B
29. C
30. D
31. A , C, and D
32. C. Thanks Chris Pereira for your feedback in our discussion
area.
33. C
34. A
35. A
36. B
37. B
38. A
40. B and C
41. A
42. A
43. D
44. A and B
45. C
46. C
47. D
48. B
49. C
50. C
51. A and C
52. C and D
53. C
54. A
55. B
56. A, B, C, and D
57. D
58. A, B, and C
59. B, C, and D
60. A
61. A and B
62. C
63. A
64. B
65. A
66. B
67. B
68. B
70. A and C
71. A
72. A, B, and C
73. A and C
74. A
75. A and D
76. A and D
77. B
78. A
79. A
80. B
81. A and D
82. B
MOCK 7
2. After execution of the code fragment below, what are the value of the variables x1, y1, and z1?
int x=10; int y =10; int z=10; int x1, y1, z1;
x1=++y;
y1=z++;
z1=z;
A. x1 = 10 , y1 = 10 and z1=10
4. Consider the following application. Assume that MyList class is declared in MyList.java
and ListManager class is declared in ListManager.java file.
public class MyList{
int size=1;
public static void main(String [] args)
{
MyList list=new MyList();
list.size=10;
ListManager lm=new ListManager();
lm.expandList(list);
System.out.println("list.size="+list.size);
}
} //end of MyList
public class ListManager{
public void expandList(MyList l)
{
l.size=l.size+10;
}
}//end of ListManager
What will be output of the above program?
. list.size=0
A. list.size=10
B. list.size=11
C. list.size=20
5. If int x = -1 then which of the following expression results in a positive value in x?
. x=x>>>32
A. x=x>>>5
B. x=x>>5
C. x=~x
6. Which of the following lines of code would print "Equal" when you run it?
7. Which of the following declarations are correct for the top level class?
. It will produce compiler warning that variable y may not have been initialized
A. It will produce compiler warning that variable x may not have been initialized
9. Consider that Parent and Child classes are defined in two different files as below:
class Parent{
public Parent(){
System.out.println("I am Parent");
}
}
class Child extends Parent{
public Child(int x){
System.out.println("I am Child");
}
public static void main(String [] args){
Child c=new Child(10);
}
}
What will be output if you try to compile and run above program?
A. It will compile successfully. It will output "I am Parent" and then "I am Child."
B. It will compile successfully. It will output "I am Child" and then "I am Parent."
. compiler error, "cannot refer inside an inner class to a static variable."
A. compiler error, "cannot refer inside an inner class to to a non-final variable newSize defined in a different
method."
. super.size
A. this.size
B. Parent.size
C. Can not access it
12. Assume that Parent and Child classes are in different files:
public class Parent{
public Parent(int x, int y)
{
System.out.println("Created Parent");
}
}//end of Parent class
public class Child extends Parent{
public Child(int x, int y){
//
}
public Child(int x, int y, int z){
System.out.println("Creating child");
this(x,y);
}
public static void main(String [] args){
Child c=new Child(1,2,3);
}
}
What will happen if you try to compile and run above program?
. It will compile successfully. It will output "Created Parent" and then "Creating child"
A. It will compile successfully. It will output "Creating child" and then "Created Parent"
B. It will not compile giving warning, "Explicit constructor invocation must be first statement in constructor."
C. It will not compile giving warning, "Expression is not a valid block statement."
16. For the following code, please consider that super class is defined in question #15:
public class MyTest extends Test{
private void demo() throws IndexOutOfBoundsException, ClassNotFoundException
{
//something here
}
}//end of MyTest class
What will happen if you try to compile above class?
A. Compiler error: Exception java.lang.ClassNotFoundException in throws clause of void MyTest.demo() is not compatible
with void Test.demo().
B. Compiler error: Cannot reduce visibility of the inherited method from Test.
B. It will not compile with error message "Can not make a static reference to the instance method named."
A. It will not compile, and reports error: "class Circle must implement inherited abstract method void Drawable.fill."
B. It will not compile, and reports error: "Method Drawable.fill requires a body instead of a semicolon."
A. Tested y.
B. Tested z.
. i = 0 j = 1
A. i = 0 j = 2
B. i = 1 j = 2
. i = 0 j = 0
A. i = 1 j = 1
B. i = 0 j = 3
C. i = 1 j =3
A. i = 1 j = 1
B. i = 0 j = 3
C. i = 1 j = 3
. i = 0 j = 0
A. i = 1 j = 1
B. i = 0 j = 3
for( i=0;i<2;i++)
{
inner:
for ( j=i; j<3; j++)
{
break inner;
}
System.out.println("i = "+i+" j = "+j);
}
Which lines would be part of the output?
. i = 0 j = 0
A. i = 1 j = 1
B. i = 0 j = 3
/** Thread2.java */
class Thread2 extends Thread{
public void run(){
System.out.println("Running Thread2");
}
public static void main(String [] args){
Thread1 t1= new Thread1();
Thread t2=new Thread2(t1);
t1.start();
t2.start();
}
}
/** End of Thread2.java*/
If you try to compile and run above code what will be result?
B. It will not compile because in Thread1 and Thread2 start() is not defined .
C. It will not compile because constructor invoked to create Thread2 with arguments (Thread1) is not defined
. It will throw an exception at th.run() because run() was called before calling start().
A. It will throw an exception at th.demo() because Thread variable th was already stopped calling stop().
How many String objects will be created after executing above lines?
. 1
A. 2
B. 3
C. 4
. It will not compile at if(s==sb) because operands on both side are not compatible
B. Both thread will get chance to run sharing CPU time
C. Neither of the thread will be able to run.
32. What changes in run() method of BussyThread will enable both threads to run?
33. Consider the following classes are in MyThread.java, YourThread.java, and Driver.java files:
public class MyThread implements Runnable{
What will be result if you try to compile and run above code?
. Compile error produced, "variable s may not have been initialized."
. Compiler error reported, "Cannot refer inside an inner class to a non-final variable 'size' defined in a different
method."
A. Compiler error reported, "Cannot refer inside an inner class to a private member variable 'list' defined in enclosing class
MyList."
B. Compiler error reported, "Cannot refer inside an inner class to a static member variable MAX_SIZE defined in enclosing
class MyList."
. publicVariable
A. privateVariable
B. SIZE
C. MAX_SIZE
56. What will be result if you try to compile and run following code?
public class Record extends String{}
. Compiler object for the method of a Child class, "Can not reduce the visibility of the inherited method."
A. Compiler object for demo() method of a Child class, "Inherited method is not compatible with void Parent.demo() throws
Exception."
. Compiler object for the method of a Child class, "Can not widen the visibility of the inherited method."
A. Compiler object for demo() method of a Child class, "Exception java.lang.Exception in throws clause of void Child.demo() is
not compatible with void Parent.demo()."
. Compiler object for the method of a Child class, "Can not widen the visibility of the inherited method."
A. Compiler object for the method of a Child class, "Return type is not compatible with void Parent.demo()."
. Compiler object for the method of a Child class, "Can not widen the visibility of the inherited method."
A. Compiler object for the method of a Child class, "inherited method void Child.demo() is not compatible with void
Parent.demo()."
B. Compiler object for the method of a Child class, "The instance method can not override the static method from Parent."
61. Consider that class Employee and Salesman are in different file called Employee.java and Salesman.java:
/** Employee.java file*/
public class Employee{
int salary=1000;
public int getSalary(){
return salary;
}
}
/** End of Employee.java file*/
/** Salesman.java file*/
public class Salesman extends Employee{
int commission =100;
public int getSalary(){
return salary+commission;
}
public static void main(String [] args){
Salesman sm = new Salesman();
Employee em = sm;
System.out.println(em.getSalary());
}
}
/** End of Salesman.java file*/
What will be result if you try to compile and run above code?
. Compiler error reported , "Type mismatch: Cannot convert from Salesman to Employee."
62. Considering following code what will be the result if you try to compile the following code:
public abstract class Test{
public void demo(){
System.out.println("demo");
}
}
63. Considering following code what will be the result if you try to compile the following code:
public class Test{
public abstract void demo();
}
A. Compiler error reported, "Abstract methods are only defined by abstract classes."
You are writing a class GroceryList that extends GenericList. Which of the following would be legal declarations of
overloading methods?
65. What will be result if you try to compile the following code?
public class Parent{
String name=null;
public Parent(String n){
name=n;
}
}
public class Child extends Parent{
String type="X";
}
A. Compiler error reported, because Parent class did not declare constructor with arguments ().
B. Compiler error reported, because Child class did not declare a constructor.
A. int
67. What will be result if you try to compile and run following code fragement?
public void demo (String [] args){
int i=1;
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
Answers:
4. D
5. D
6. A
7. D
8. B and D
9. A and D
10. C and D
11. A
12. B
13. B
14. D
15. C and D
17. B, C, D and E
18. A
20. D
21. C
22. B
23. D
24. A, B, and C
25. C and D
26. A and B
27. D
28. A and B
29. C
30. D
31. C
32. C
33. A
34. C
35. A and B
36. B
37. D
38. A
39. A
40. C and D
41. A
42. A
43. B
44. B
45. C
46. C
47. A
48. B
49. A and B
50. B
51. B and C
52. B
`````````````````````````````````````````````````````````````````````````````````````````````````````````````````
1.What is the result when you compile and run the following code?
class Top {
3. What is the result of the following program, when you compile and run?
4. What is the output when you compile and run the following code fragment?
class MyTest {
5. Select all the exceptions thrown by wait() method of an Object class, which you can
replace in the place of xxx legally?
6. Which of the following are examples of immutable classes , select all correct
answer(s)?
A) String
B) StringBuffer
C) Double
D) Integer
7. Select the correct answer for the code fragment given below?
8. What is the result when you compile and run the following code?
A) int100
B) byte
C) aString
D) a-Big-Integer
E) Boolean
F) strictfp
10. Select the equivalent answer for the code given below?
boolean b = true;
if ( b ) {
x = y;
} else {
x = z;
}
A) x = b ? x = y : x = z ;
B) x = b ? y : z ;
C) b = x ? y : z ;
D) b = x ? x = y : x = z ;
class Vehicle {
13. Java source files are concerned which of the following are true ?
A) Java source files can have more than one package statements.
B) Contains any number of non-public classes and only one public class
C) Contains any number of non-public classes and any number of public classes
D) import statements can appear anywhere in the class
E) Package statements should appear only in the first line or before any import statements of
source file
int a = -1;
int b = -1;
a = a >>> 31;
b = b >> 31;
A) a = 1, b =1
B) a = -1, b -1
C) a = 1, b = 0
D) a = 1, b = -1
15. What is the value of a , when you compile and run the following code?
int a = 10;
int b = 9;
int c = 7;
a = a ^ b ^ c;
System.out.println ( a );
}
A) 10
B) 9
C) 7
D) 4
16. The following code has some errors, select all the correct answers from the
following?
A) At class declaration
B) myTest() method declaration
C) Test() method declaration
D) No errors, compiles successfully
17. At what point the following code shows compile time error?
class A {
A() {
System.out.println("Class A constructor");
}
}
class B extends A {
B() {
System.out.println("Class B constructor");
}
}
A) s == s1
B) s.equals(s1);
C) s = s1;
D) None of the above
19. Select all correct answers about what is the definition of an interface?
A) It is a blue print
B) A new data type
C) Nothing but a class definition
D) To provide multiple inheritance
20. Select all correct answers from the following code snippets?
A) // Comments
import java.awt.*;
package com;
B) import java.awt.*;
// Comments
package com;
C) package com;
import java.awt.*;
// Comments
D) // Comments
package com;
import java.awt.*;
public class MyTest {}
21. What is the result when you compile and run the following code?
A) Prints 0 to 9 in sequence
B) No output
C) Runtime error
D) Compile time error
22. There are two computers are connected to internet, one computer is trying to open a
socket connection to read the home page of another computer, what are the possible
exceptions thrown while connection and reading InputStream?.
A) IOException
B) MalformedURLException
C) NetworkException
D) ConnectException
23. What is the result from the following code when you run?
import java.io.*;
class A {
24. What is the result from the following code when you run?
import java.io.*;
class A {
A() {
System.out.println ("Executing class A constructor");
}
A(int a) throws Exception {
System.out.println ("Executing class A constructor");
throw new IOException();
}
25. What is the result when you compile and run the following code?
A) 120;
B) Compile time error while declaring variables
C) Compile time error while multiplication
D) None of the above
27. Which subclasses of the Component class will display the MenuBar?
A) Window, Applet
B) Applet, Panel
C) Frame
D) Menu, Dialog
A) java.awt.TextArea.SCROLLBARS_NONE
B) java.awt.TextArea does not generate Key events
C) java.awt.TextField generates Key events and Action events
D) java.awt.TextArea can be scrolled using the <-- and --> keys.
31. What is the result if you try to compile and run the following code ?
public class MyTest {
}
public static void main(String[] args) {
myTest();
myMethod();
}
import java.io.*;
}
}
import java.io.*;
class FileWrite {
public static void main(String args[]) {
try {
String strString = "Now is the time to take Sun Certification";
char buffer[] = new char[strString.length()];
strString.getChars(0, strString.length(), buffer, 0);
FileWriter f = new FileWriter("MyFile1.txt");
FileWriter f1 = f;
f1.close();
for (int i=0; i < buffer.length; i += 2) {
f.write(buffer[i]);
}
f.close();
34. Which line of the program could be throwing an exception, if the program is as listed
below. Assume that "MyFile2.txt" is a read only file.
import java.io.*;
class FileWrite {
public static void main(String args[]) {
try {
String strString = "Updating the critical data section"
char buffer[] = new char[strString.length()];
strString.getChars(0, strString.length(), buffer, 0);
FileWriter f = new FileWriter("MyFile1.txt");
FileWriter f1 = f;
for (int i=0; i < buffer.length; i += 2) {
f1.write(buffer[i]);
}
f1.close();
36. Using File class, you can navigate the different directories and list all the files in the
those directories?
A) True
B) False
A) FileOutputStream(FileDescriptor fd)
B) FileOutputStream(String fileName, boolean append)
C) FileOutputStream(RandomAccessFile raFile)
D) FileOutputStream( String dirName, String filename)
39. In an applet programing the requirement is that , what ever the changes you do in
the applets graphics context need to be accumulated to the previous drawn information.
Select all the correct code snippets?
40. How can you load the image from the same server where you are loading the applet,
select the correct answer form the following?
41. Which of the following answers can be legally placed in the place of XXX?
class Check {
Check() { }
}
42. There are 20 threads are waiting in the waiting pool with same priority, how can
you invoke 15th thread from the waiting pool?.
44. The thread run() method has the following code, what is the result when the thread
runs?
try {
sleep( 200 );
System.out.println( "Printing from thread run() method" );
} catch ( IOException ie) { }
45. What is the result when you compile and run the following code?
import java.awt.*;
A) Double
B) Boolean
C) Integer
D) Byte
D) Math.round(3.4) returns 3
Math.round(-3.4) returns -------
51. Select from the following which is legal to put in the place of XXX?
52. If you save and compile the following code, it gives compile time error. How do you
correct the compile time error?
54. What is the result when you compile and run the following code?
import java.util.*;
public class MyVector {
55. What is the output on the screen when compile and run the following code?
A) 1
B) 2
C) -1
D) -2
A) AWTEvent
B) EventObject
C) InputEvent
D) MouseEvent
A) As a HashMap
B) As a Queue
C) As a TreeSet
D) As a Stack
A) Compilation error
B) Runtime error
C) Compile successfully, nothing is printed.
D) inside throwMethod. followed by caught: java.lang.IllegalAccessException: demo
Answers
Answer 1:
Explanation:
Generally static methods can be overridden by static methods only .. Static methods may not be
overridden by non static methods..
Answer 2:
Explanation:
Answer C) will cause an "ArrayOutOfBoundsException" if you do not pass the command line
arguments to the Java Program. A) and B) will work without any problem.
Answer 3:
Answer 4:
Explanation:
Static methods are determined at compile time but the non static ( instance methods ) methods
are identified at runtime using Run Time Type Identification ( RTTI).
Answer 5:
Explanation:
The wait() method of an Object class throws InterruptedException when the thread moving from
running state to wait state. If the value of timeout is negative or the value of nanos is not in the
range 0-999999 then wait() method throws IllegalArgumentException exception at runtime. If the
current thread is not the owner of this object's monitor then it throws IllegalMonitorStateException
exception. Click here for more information from Java Documentation.
Answer 6:
A) String
C) Double
D) Integer
Explanation:
String, Integer, Double are immutable classes, once assign a values it cannot be changed. Please
refer the wrapper classes for more information on Integer, and Double.
Answer 7:
Explanation:
Assigning or interchanging the object references does not change the values, but if you change the
values through object references , changes the values .
Answer 8:
B) Runtime error
C) ArrayOutOfBoundsException
Explanation:
This piece of code throws an ArrayOutOfBoundsException at runtime . If you modify the code int
myArray[] = new int[1]; to int myArray[] = new int[2]; , it prints 1 on the screen. The changes
you made on the array subscript seen by the caller.
Answer 9:
A) int 100
C) aString
E) Boolean
Explanation:
The byte, strictfp are Java keywords and cannot be defined as identifiers, the a-Big-Integer has "-"
which is not a valid identifier. The identifiers must starts with letters, $, or _ ( underscore),
subsequent characters may be letters, dollar signs, underscores or digits, any other combination
will gives you the compiler error.
Answer 10:
B) x = b ? y : z ;
Explanation
If b is true the value of x is y, else the value is z. This is "ternary" operator provides the way to
simple conditions into a single expression. If the b is true, the left of ( : ) is assigned to x else
right of the ( : ) is assigned to x. Both side of the ( : ) must have the data type.
Answer 11:
Explanation:
Multidimensional arrays in Java are just arrays within arrays. Multidimensional arrays are defined
as rows and columns. The outer array must be initialized. If you look at the answers the outer
arrays are initialized.
Answer 12:
Explanation:
In Java final variables are treated as constants ( comparing to other languages like Visual Basic
and etc.) , once it is initialized you cannot change the values of primitive, if final variables are
object references then you cannot assign any other references.
Answer 13:
B) Contains any number of non-public classes and only one public class
E) Package statements should appear only in the first line or before any import statements of
source file
Explanation:
The source files always contains only one package statement, you cannot define multiple package
statements and these statements must be before the import statements. At any point of time Java
source files can have any number of non-public class definitions and only one public definition
class. If you have any import statements those should be defined before class definition and after
the package definition.
Answer 14:
D) a = 1, b = -1
Explanation:
The operator >>> is unsigned right shift, the new bits are set to zero, so the -1 is shifted 31 times
and became 1 ( because a is defined as integer ). The operator >> is signed right shift operator,
the new bits take the value of the MSB ( Most Significant Bit ) . The operator << will behave like
same as >>> operator. The sifting operation is applicable to only integer data types.
Answer 15:
D) 4
Explanation:
The operator is bitwise XOR operator. The values of a, b, c are first converted to binary
equivalents and calculated using ^ operator and the results are converted back to original format.
Answer 16:
Explanation:
The abstract methods cannot have body. In any class if one method is defined as abstract the
class should be defined as abstract class. So in our example the Test() method must be redefined.
Answer 17:
Explanation:
According to the inheritance rules, a parent class references can appear to the child class objects
in the inheritance chain from top to bottom. But in our example class B, and class C are in the
same level of hierarchy and also these two classes does not have parent and child relationship
which violates the inheritance rules.
Answer 18:
A) s == s1
B) s.equals(s1);
Explanation:
The string objects can be compared for equality using == or the equals() method ( even though
these two have different meaning ). In our example the string objects have same wording but both
are different in case. So the string object object comparison is case sensitive.
Answer 19:
A) It is a blue print
B) A new data type
D) To provide multiple inheritance
Explanation:
One of the major fundamental change in Java comparing with C++ is interfaces. In Java the
interfaces will provide multiple inheritance functionality. In Java always a class can be derived
from only one parent, but in C++ a class can derive from multiple parents.
Answer 20:
C) package com;
import java.awt.*;
// Comments
D) // Comments
package com;
import java.awt.*;
public class MyTest {}
Explanation
In a given Java source file, the package statement should be defined before all the import
statement or the first line in the .java file provided if you do not have any comments or JavacDoc
definitions. The sequence of definitions are:
// Comments ( if any)
Package definition
Multiple imports
Class definition
Answer 21:
Explanation:
The code fails at the time Math class instantiation. The java.lang.Math class is final class and the
default constructor defined as private. If any class has private constructors , we cannot instantiate
them from out the class ( except from another constructor ).
Answer 22:
A) IOException
B) MalformedURLException
Explanation:
In Java the the URL class will throw "MalformedURLException while construncting the URL, and
while reading incoming stream of data they will throw IOException..
Answer 23:
Explanation:
In Java the constructors can throw exceptions. If parent class default constructor is throwing an
exception, the derived class default constructor should handle the exception thrown by the parent.
Answer 24:
Explanation:
In Java the constructors can throw exceptions. According to the Java language exceptions, if any
piece of code throwing an exception it is callers worry is to handle the exceptions thrown by the
piece of code. If parent class default constructor is throwing an exception, the derived class default
constructor should handle the exception thrown by the parent. But in our example the non default
constructor is throwing an exception if some one calls that constructor they have to handle the
exception.
Answer 25:
Explanation:
This does not compile because according to the arithmetic promotion rules, the * ( multiplication )
represents binary operator. There are four rules apply for binary operators. If one operand is
float,double,long then other operand is converted to float,double,long else the both operands are
converted to int data type. So in our example we are trying put integer into byte which is illegal.
Answer 26:
A) setBounds(), setVisible(), setFont()
B) add(), remove()
C) setEnabled(), setVisible()
Explanation:
The component class is the parent class of all AWT components like Button, List, Label and etc.
Using these methods you can set the properties of components. The add(), remove() methods are
used to add PopMenu and to remove MenuComponent.
Answer 27:
C) Frame
Explanation:
Java supports two kinds of menus, pull-down and pop-up menus. Pull-down menus are accessed
are accessed via a menu bar. Menu bars are only added to Frames.
Answer 28:
Explanation:
In Java AWT each container has it's own default layout manager implemented as part of
implementation. For example Frame has default layout manager is BorderLayout , Applet has
FlowLayout and etc. The Canvas is kind of component where you can draw custom drawings. The
Canvas generates Mouse, MouseMotion, and Key events .
Answer 29:
Explanation:
The java.awt.List has methods to select , count the visible rows.
void addItem(String s) --> adds an item to the bottom of the list
int getRows() --> returns the number of visible lines in the list
int[] getSelectedIndexes() --> returns array of indexes currently selected items
int getItemCount() --> returns the number of items in the list
String[] getSelectedItems() --> returns array of string values of currently selected items
Answer 30:
A) java.awt.TextArea.SCROLLBARS_NONE
C) java.awt.TextField generates Key events and Action events
D) java.awt.TextArea can be scrolled using the <-- and --> keys.
Explanation:
The TextArea and TextField are the subclasses of TextComponent class. The TextArea has static
fields to give you the functionality of horizontal and vertical scroll bars. These are the following
fields:
java.awt.TextArea.SCROLLBARS_BOTH
java.awt.TextArea.SCROLLBARS_NONE
java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY
java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY
The TextArea and TextField will generate Key events and TextField will generate Action events
apart from the Key events.
Answer 31:
Explanation:
In Java there are two types of methods , static and non static methods. Static methods are belong
to class and non static methods are belongs to instances. So from a non static method you can call
static as well as static methods, but from a static method you cannot call non static methods
( unless create a instance of a class ) but you can call static methods.
Answer 32:
Explanation:
While constructing the FileReader object, if the file is not found in the file system the
"FileNotFoundException" is thrown. If the input stream is closed before reading the stream throws
IOException.
Answer 33:
Explanation:
While writing to a IO stream if the stream is closed before writing throws an IOException. In our
example the f ( stream ) is closed via f1 reference variable before writing to it.
Answer 34:
Explanation:
Constructing the FileWriter object, if the file already exists it overrides it (unless explicitly specified
to append to the file). FileWriter will create the file before opening it for output when you create
the object. In the case of read-only files, if you try to open and IOException will be thrown.
Answer 35:
Explanation:
The File class has three methods to create empty files, those are createNewFile(),
createTempFile(String prefix, String suffix) and createTempFile(String prefix, String suffix, File
directory).
File class has two utility methods mkdir() and mkdirs() to create directories. The mkdir() method
creates the directory and returns either true or false. Returning false indicates that either directory
already exists or directory cannot be created because the entire path does not exists. In the
situation when the path does not exists use the mkdirs() method to create directory as well as
parent directories as necessary.
Answer 36:
A) True
Explanation:
File class can be used to navigate the directories in the underlying file system. But in the File class
there is no way you change the directory . Constructing the File class instance will always point to
only one particular directory. To go to another directory you may have to create another instance
of a File class.
Answer 37:
A) FileOutputStream(FileDescriptor fd)
B) FileOutputStream(String fileName, boolean append)
Explanation:
The valid FileOutputStream constructors are:
FileOutputStream(String fileName)
FileOutputStream(File file)
FileOutputStream(FileDescriptor fd)
Answer 38:
Explanation:
The Font class gives you to set the font of a graphics context. While constructing the Font object
you pass font name, style, and size of the font. The font availability is dependent on platform. The
Font class has three types of font names called " Serif", "SanSerif", Monospaced" these are called
in JDK 1.1 and after "Times Roman", Helavatica" and "Courier".
Answer 39:
Explanation:
If you want accumulate the previous information on the graphics context override the update()
and inside the method call the paint() method by passing the graphics object as an argument. The
repaint() method always calls update() method
Answer 40:
Explanation:
The Applet and Toolkit classes has a method getImage() , which has two forms:
getImage(URL file)
getImage(URL dir, String file)
These are two ways to refer an image in the server . The Applet class getDocumentBase()
methods returns the URL object which is your url to the server where you came from or where
your image resides.
Answer 41:
D) Object, Check, ICheck
Explanation:
The instanceof operator checks the class of an object at runtime. In our example o refers to Object
class and Check and ICheck refers to the subclasses of Object class. Due to the inheritance
hierarchy Check and ICheck returns true.
Answer 42:
Explanation:
There is no way to call a particular thread from a waiting pool. The methods notify() will calls
thread from waiting pool, but there is no guaranty which thread is invoked. The method notifyAll()
method puts all the waiting threads from the waiting pool in ready state.
Answer 43:
Explanation:
The keyword controls accessing the single resource from multiple threads at the same time. A
method or a piece of code can be synchronized, but there is no way to synchronize a calls. To
synchronize a method use synchronized keyword before method definition. To synchronize block of
code use the synchronized keyword and the arbitrary instance.
Answer 44:
Explanation:
The IOException never thrown here. The exception is thrown is InterruptedException. To correct
instead of catching IOException use InterruptedException.
Answer 45:
Explanation:
The Frame is not going to be visible unless you call setVisible(true) method on the Frame's
instance. But the frame instance is available in computers memory. If do not set the size of the
Frame you see default size of the frame ( i.e.. in minimized mode)
Answer 46:
Explanation:
The abstract methods does not have method bodies. In any given class if one method is defined
as abstract the class must defined as abstract class.
Answer 47:
Explanation:
The toString() is defined in Object class the parent all classes which will gives you the string
representation of the object's state. This more useful for debugging purpose. The wait(), notify(),
notifyAll() methods are also defined in Object class are very helpful for Thread communication.
These methods are called only in synchronized methods.
Answer 48:
Explanation:
To define transient variables just include "transient" keyword in the variable definition. The
transient variables are not written out any where, this is the way when you do object serialization
not to write the critical data to a disk or to a database.
The "synchronized" keyword controls the single resource not to access by multiple threads at the
same time. The synchronized keyword can be applied to a method or to a block of code by passing
the arbitrary object instance name as an argument.
Answer 49:
A) Double
C) Integer
D) Byte
Explanation:
In Java all the primitive data types has wrapper classes to represent in object format and will
throw "NumberFormatException". The Boolean does not throw "NumberFormatException" because
while constructing the wrapper class for Boolean which accepts string also as an argument.
Answer 50:
D) Math.round(3.4) returns 3
Math.round(-3.4) returns -3
Explanation:
The Math class abs() method returns the absolute values, for negative values it just trips off the
negation and returns positive absolute value. This method returns always double value.
The method ceil(), returns double value not less than the integer ( in our case 3 ). The other ways
to say this method returns max integer value . ( All the decimals are rounded to 1 and is added to
integer value ). For negative values it behaves exactly opposite.
The method floor() is exactly reverse process of what ceil() method does.
The round() method just rounds to closest integer value.
Answer 51:
Explanation:
The static methods are class level methods to execute those you do not need a class instance. If
you try to execute any non static method or variables from static methods you need to have
instance of a class. In our example we need to have OuterClass reference to execute InnerClass
method.
Answer 52:
Explanation:
In Java it is possible to declare a class inside a method. If you do this there are certain rules will
be applied to access the variables of enclosing class and enclosing methods. The classes defined
inside any method can access only final variables of enclosing class.
Answer 53:
C) This is convention adopted by Sun , to insure that there is no ambiguity between packages and
inner classes.
Explanation:
This is convention adopted to distinguish between packages and inner classes. If you try to use
Class.forName() method the call will fail instead use getCLass().getName() on an instance of inner
class.
Answer 54:
Explanation:
The method in Vector class , addElement() returns type of void which you cannot return in our
example. The myVector() method in our MyVector class returns only type of Vector.
Answer 55:
C) -1
Explanation:
Internally the x value first gets inverted ( two's compliment ) and then shifted 1 times. First when
it is inverted it becomes negative value and shifted by one bit.
Answer 56:
C) InputEvent
Explanation:
The InputEvent class has method getWhen() which returns the time when the event took place
and the return type is long.
Answer 57:
B) getSource() method is defined in java.util.EventObject class
C) getID() method is defined in java.awt.AWTEvent class
Explanation:
The super class of all event handling is java.util.EventObject which has a method called
getSource() , which returns the object that originated the event.
The subclass of EventObject is AWTEvent has a method getID() , which returns the ID of the event
which specifies the nature of the event.
Answer 58:
Explanation:
The event listeners are instance of the class that implements listener interface . An event source is
an instance of class like Button or TextField that can register listener objects and sends
notifications whenever event occurs.
Answer 59:
B) As a Queue
D) As a Stack
Explanation:
This implements java.util.List interface and uses linked list for storage. A linked list allows
elements to be added, removed from the collection at any location in the container by ordering the
elements. With this implementation you can only access the elements in sequentially.You can
easily treat the LinkedList as a stack, queue and etc., by using the LinkedList methods.
Answer 60:
A) Compilation error
Explanation:
The method throwMethod() is throwing and type Exception class instance, while catching the
exception you are catching the subclass of Exception class.