Java MCQ'S
Java MCQ'S
protected BOTTOM;
}
class Output
{
public static void main(String args[])
What{ will be the output of the following Java code snippet?
double x = 3.14;
import intjava.util.*;
y = (int) Math.ceil(x);
class System.out.print(y);
Arraylists
{ }
} public static void main(String args[])
{
ArrayLists obj = new ArrayLists();
obj.add("A");
obj.add("B");
obj.add("C");
obj.add(1, "D");
System.out.println(obj);
}
What will be the output of the following Java code?
}
class newthread extends Thread
{
Thread t;
newthread()
{
t1
Which = new
one ofThread(this,"Thread_1");
the following is not an access modifier?
t2 = new Thread(this,"Thread_2");
t1.start();
t2.start();
}
public void run()
{
What is the stored in the object obj in following lines of Java code?
t2.setPriority(Thread.MAX_PRIORITY);
System.out.print(t1.equals(t2));
Which of these keywords is used to make a class?
}
}
class multithreaded_programing
{
public static void main(String args[])
{
Which of the following is a valid declaration of an object of class Box?
What is the return type of a method that does not return any value?
What is the process of defining more than one method in a class differentiated by
Which of the following is a method having same name as that of it’s class?
Which keyword is used by the method to refer to the object that invoked it?
Which of the following is a method having same name as that of its class?
Which operator is used by Java run time implementations to free the memory of an object when it is no longer needed?
How to get prints of shared object memory maps or heap memory maps for a given
What is the process of defining two or more methods within same class that have s
What is the process of defining a method in terms of itself, that is a method that calls
Which of these is used to access a member of class before object of that class is cre
What is the process by which we can control what parts of a program can access th
Which of these access specifier must be used for class so that it can be inherited by
Which one of the following is not an access modifier?
Which of the following modifier means a particular variable cannot be accessed wit
How many copies of static and class variables are created when 10 objects are create
Which of these keywords is used to prevent content of a variable from being modifi
String in Java is a?
Which of these method of String class is used to obtain character at specified index?
Which of these keywords is used to refer to member of base class from a subclass?
Which of these method of String class can be used to test to strings for equality?
Which of these is the method which is executed first before execution of any other
What is the process of defining more than one method in a class differentiated by
Which of these can be used to differentiate two or more methods having the same
Which of these data type can be used for a method having a return statement in it?
Which of these data types is used by operating system to manage the Recursion in J
Which of these will happen if recursive method does not have a base case?
Which of this keyword can be used in a subclass to call the constructor of superclass
What is the process of defining a method in a subclass having same name & type sig
Which mode allows us to run program interactively while watching source code and
Which of these class is superclass of String and StringBuffer class?
Which of these operators can be used to concatenate two or more String objects?
public class genericstack <E>
{
Stack <E> stk = new Stack <E>();
public void push(E obj)
{
What will be the output of the following Java code?
stk.push(obj);
import
} java.util.*;
publicE class
public pop()genericstack <E>
{ {
Which Stack <E>
Eofobj
this stk = new
= method of Stack
stk.pop(); <E>(); is used to obtain a length of String object?
class String
public
returnvoid push(E obj)
obj;
Which of these method of class String is used to extract a single character from a Str
} {
Which
} stk.push(obj);
of these constructors is used to create an empty String object?
} class Output
public
{ E pop()
Which of these is an incorrect statement?
{public static void main(String args[])
{ E obj = stk.pop();
return obj;
genericstack <String> gs = new genericstack<String>();
} gs.push("Hello");
} System.out.println(gs.pop());
class} Output
{}
public static void main(String args[])
{
genericstack <Integer> gs = new genericstack<Integer>();
gs.push(36);
System.out.println(gs.pop());
}
}
Which of these keywords must be used to handle the exception thrown by try block in some rational manner?
Which of these class is related to all the exceptions that cannot be caught?
Which of these exceptions will occur if we try to access the index of an array beyond
What is the use of try & catch?
Which of these keywords are used for the block to be examined for exceptions?
Which of these keywords are used for the block to handle the exceptions generated
Which of these keywords are used for generating an exception manually?
What will happen if two thread of the same priority are called to be processed simultaneously?
Deadlock is a situation when thread is waiting for other thread to release acquired o
Which of the following will ensure the thread will be in running state?
Which of these method is used to tell the calling thread to give up a monitor and g
What will be the output of the following Java program?
class newthread extends Thread
{
What
Thread will
t; be the output of the following Java program?
String name;
class newthread threadname)
newthread(String extends Thread
{ {
Thread
namet;= threadname;
String name;
t = new Thread(this,name);
newthread(String
t.start(); threadname)
} {
name
public = threadname;
void run()
t ={ new Thread(this,name);
t.start();
}
}
public void run()
What will be the output of the following Java program?
class newthread extends Thread
{
Thread t;
String name;
What does AWT stands
newthread(String for?
threadname)
{
name
Which of=these
threadname;
is used to perform all input & output operations in Java?
t = new Thread(this,name);
t.start();
}
Which of these is a type of stream in Java?
public void run()
{
}
Which of these classes are used by Byte streams for input and output operation?
}
class multithreaded_programing
Which
{ of these classes are used by character streams for input and output operatio
Whatpublic
will be the output
static of the following
void main(String args[]) Java program if input given is
‘abcqfghqbcd’?
{
Whatnewthread
will be theobj1 = new
output newthread("one");
of the following Java program if input given is
class Input_Output
newthread
“abc’def/’egh”? obj2 = new newthread("two");
{ try
public
class static void main(String args[]) throws IOException
{Input_Output
{ { will System.out.print(obj1.t.equals(obj2.t));
What be the output of the following Java program?
char c; void main(String args[]) throws IOException
} static
public
{ BufferedReader
class catch(Exception
output obj
e) = new BufferedReader(new
InputStreamReader(System.in));
{ {char c;
do
System.out.print("Main
public obj =thread
static void main(String
BufferedReader interrupted");
args[])
new BufferedReader(new
{
Which }exception
{
InputStreamReader(System.in));
is thrown
c = (char) obj.read();by read() method?
} do StringBuffer c = new StringBuffer("Hello");
} System.out.print(c);
{System.out.println(c.length());
} } while(c != 'q');
c = (char) obj.read();
} }System.out.print(c);
Which
} of these is used to read a string from the input stream?
} while(c!='\'');
}
}
Which of these class is used to read characters and strings in Java from console?
What will be the output of the following Java program if input given is “Hello stop
World”?
class Input_Output
{
Whatpublic
will be the output
static of the following
void main(String args[]) Java program?
throws IOException
{
classstring
output str;
{ BufferedReader obj = new BufferedReader(new
public static void main(String args[])
InputStreamReader(System.in));
{ do
{StringBuffer c = new StringBuffer("Hello");
Which of StringBuffer
(char)c1
the=following
str =isnew
not StringBuffer(" World");
a class of java.util.regex?
obj.readLine();
c.append(c1);
System.out.print(str);
}System.out.println(c);
while(!str.equals("strong"));
}}
}} is the significance of Matcher class for regular expression in java?
What
Which of these is a mechanism for naming and visibility control of a class and its co
Which of this access specifies can be used for a class so that its members can be acc
Which of these access specifiers can be used for a class so that its members can be a
Which of the following is the correct way of importing an entire package ‘pkg’?
What will be the output of the following Java program?
package pkg;
What
classwill be the output of the following Java program?
display
{
package
intof pkg;
x; these
Which
class output can be used to fully abstract a class from its implementation?
void show()
{ {
public
if (x >static
1) void main(String args[])
{ System.out.print(x + " ");
} StringBuffer s1 = new StringBuffer("Hello");
} s1.setCharAt(1, x);
classSystem.out.println(s1);
packages
{ }
} public static void main(String args[])
Which of these access specifiers can be used for an interface?
{
Which display[]
of the following
arr=newisdisplay[3];
the correct way of implementing an interface salary by cl
for(int
What will i=0;i<3;i++)
be the output of the following Java program?
arr[i]=new display();
arr[0].x
interface = 0;
calculate
{ arr[1].x = 1;
arr[2].x
void cal(int= item);
2;
} for (int i = 0; i < 3; ++i)
arr[i].show();
class display implements calculate
{ }
} int x;
public void cal(int item)
What will be the output of the following Java program?
interface
What will becalculate
the output of the following Java program?
{
void cal(int
interface calculateitem);
{ }
classint displayA
VAR = implements
0; calculate
{ void cal(int item);
Which intof x; the following access specifiers can be used for an interface?
}
public void cal(int
class display item) calculate
implements
Which {{ of the following is the correct way of implementing an interface A by class B?
xint= x;
item * item;
} public void cal(int item)
} {
classtype
What displayB implements
of variable
if (item<2) can becalculate
defined in an interface?
{ x = VAR;
int x;else
Whatpublic
does void an interface
cal(int contain?
item)
x = item * item;
{ }
} x = item / item;
class } interfaces
What
} type of methods an interface contain by default?
{
class interfaces
{ happens
What public staticwhen a constructor
void main(Stringisargs[])
defined for an interface?
public
{ static void main(String args[])
{ display[] arr=new display[3];
displayA arr1 = new displayA;
displayB arr2 = new displayB;
for(int i=0;i<3;i++)
arr1.x = 0; display();
arr[i]=new
What happens
arr2.x when we access the same variable defined in two interfaces impleme
= 0;
arr[0].cal(0);
arr1.cal(2);
arr[1].cal(1);
arr2.cal(2);
arr[2].cal(2);
System.out.print(arr1.x
Can “abstract” keyword be used
System.out.print(arr[0].x+" + "with
" +" arr2.x);
+constructor,
arr[1].x + " Initialization
" + arr[2].x); Block, Instance Initiali
} }
} }
Which method is used to verify the actual and expected results in Junits?
How to let junits know that they need to be run using PowerMock?
How can we simulate if then behavior in Junits?
What is used to inject mock fields into the tested object automatically?
0 1 2
0.00999999999999999
0.01 0.01 0.01
0.00999999999999999 0.01
38 39 40
b cannot contain value 100, limited by its * operator has converted b * 50 into
range int, which can not be converted to b cannot contain value 50
byte without casting
EU UE VE
38 43 39 44 295 300
b is : 2 b is : 1 Compilation Error
1 1 1 0 1 0 3
int arr[] = new int[5] int [] arr = new int[5] int arr[] = new int[5]
It is necessary to use new operator to Array can be initialized using comma Array can be initialized when they
initialize an array separated expressions surrounded by are declared
curly braces
3 0 4
truetrue falsefalse 1
Every class must contain a main() Applets do not require a main() There can be only one main()
method method at all method in a program
Public method is accessible to all other Public method is accessible only to Public method can only be called
classes in the hierarchy subclasses of its parent class by object of its class
All object of a class are allotted memory If a function is defined public it can
for the all the variables defined in the be accessed by object of other class main() method must be made
public
class by inheritation
Constructors cannot be synchronized in Java does not provide default copy Constructor can have a return
Java constructor type
It can contain return type It can take any number of parameters It can have any non access
modifiers
1 0
Protected constructor can be called Protected constructor can only be Protected constructor can be
directly called using super() used outside package
The thread continues its operation Garbage collection cannot happen The thread is paused while
until the thread is running garbage collection runs
1 0
Any class can instantiate objects of class Objects of class A can be instantiated Inherited class can instantiate
A only within the class where it is objects of class A
declared
default and final default and static public, static and final
Final class cause compilation failure Final class cannot be instantiated Final class cause runtime failure
1, 10 10, 10 10 1
1 0
static methods can call other static static methods must only access static methods can not refer to
methods only static data this or super in any way
Variables declared as final occupy final variable must be initialized at Arrays in java are implemented
memory the time of declaration as an object
System stops the program after some After 1000000 calls it will be
An infinite loop occurs time automatically stopped
2 3 7
0 2 Runtime error
+ = &
get() Sizeof() lengthof()
CHARAT() chatat() charAt()
String() String(void) String(0)
String objects are immutable, they canno String object can point to some other rStringBuffer class is used to store st
H Hello
Runtime Error
0 36 Runtime error
try
finally thrown
try block need not to be followed by catchtry block can be followed by finally blotry can be followed by both catch a
Hello World HelloWOrld
A B Complilation Error
It’s a process of handling situations whe It’s a process by which many thread arIt’s a process by which a method is
0 1 1
1 0
truetrue
1 0 truetrue
get() ThreadPriority() getPriority()
sleep() terminate() suspend()
0 1 4
0 1 1
It’s a process in which two different proc It’s a process in which two or more pa It’s a process in which many differ
Anyone will be executed first lexographicaBoth of them will be executed simulta None of them will be executed
By multithreading CPU idle time is minimi By multitasking CPU idle time is minim Two thread in Java can have the sa
Thread[5,main] Thread[main,5] Thread[main,0]
4 5 0
1 0
Avoid using multiple threads Avoid hold several locks at once Execute foreign code while holding
run() method calls start() method and runrun() method creates new thread run() method can be called directly
Calling SetPriority() method on a Thread o Calling notify() method on an object Calling wait() method on an object
interpretes pattern in the string Performs match in the string interpreted both pattern and perfo
Replace all characters that matches patterReplace first subsequence that matchesReplace all other than first subseq
An event is an object that describes a stat An event is an object that describes a An event is an object that describ
KeyListener() addKistener() addKeyListener()
java.io java.lang java.net
012 0 2 4 0 0 4
Compilation failure Runtime Exception The JVM is not able to identify the
1 0
assert() equals() ==
<dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.junit</groupId> <groupId>mock.junit</groupId
<artifactId>junit</artifactId> <artifactId>junit</artifactId> >
<version>4.8.1</version> <version>4.8.1</version> <artifactId>junit</artifactId>
</dependency> </dependency> <version>4.8.1</version>
</dependency>
1 0
boolean b4 = ‘true’ C
Depends on the order() method D
B
3 A
EnumNotDefined Exception B
Compilation Error D
getEnum() B
Precision D
Bigdecimal D
0.009999999999999998 A
0.009999999999999998
DateConverter A
java.util.DateTime A
Time diffInMilli =
java.time.Duration.between(dateTime1, A
dateTime2).toMillis();
41 C
1 2 3 4 5 6 7 8 9 10 B
Compilation error D
UF A
int arr[] = int [5] new D Operator new must be succeeded by array type and
array size.
Array can be initialized using both new and comma
separated expressions surrounded by curly braces
None of the mentioned A example : int arr[5] = new int[5]; and int arr[] = { 0,
1, 2, 3, 4};
“this” and “super” can be used in a The constructor cannot have a return type. It should
C create and return new objects. Hence it would give
constructor a compilation error.
Class.getInstance creates object if class does Class class provides list of methods for use like
not have any constructor D getInstance().
Constructor returns a new object with variables
Constructor cannot throw an exception B defined as in the class. Instance variables are newly
created and only one copy of static variables are
created.
The thread and garbage collection do not C The thread is paused when garbage collection runs
interfere with each other which slows the application performance.
Recursion D
protected C
Recursion C
protected members of a class can be private members of a class can not be inherited by
inherited by a subclass, and become private C a subclass.
members of the subclass
classes within the same package as class A If we make any class constructor private, we cannot
can instantiate objects of class A B create the instance of that class from outside the
class.
Java defines a peer class of String, called Strings in Java are immutable that is they can not be
StringBuffer, which allows string to be altered B modified.
If a method is returning a value the calling Even if a method is returning a value, it is not
statement must have a variable to store that D
value necessary to store that value.
Compilation error
Compilation Error B
Complilation Error
ArrayIndexOutOfBoundsException is a built in
exception that is caused when we try to access an
index location which is beyond the length of an
ArrayIndexOutOfBoundsException D array.
All of the mentioned D
check try is used for the block that needs to checked for
A exception.
check B
check C
try need not to be followed by anything D try must be followed by either catch or finally block
Compilation Error B
Compilation Error A
Compilation Error D
Compilation Error C
System A
getMessage() returns a description of the
obtainException() B exception.
displayStackTrace() B
Class A
Complilation Error
1 & 256 C
stop() C
Thread[New Thread,5,main] D
5
D The default priority given to a thread is 5.
abcqfghq C
readLine() C
InputStreamReader A
Hexlo C
None of the Mentioned C
@RunWith(PowerMockRunner.class) signifies
to use PowerMock JUnit runner. Along with
that @PrepareForTest(User.class) is used to
declare the class being tested.
mockStatic(Resource.class) is used to mock the
@RunWith(PowerMockRunner.class) D static methods
Mockito.when(mockList.size()).thenReturn(100
); assertEquals(100, mockList.size()); is the
Mockito.if(..).then(..); C usage to implement if and then behavior
<dependency>
<groupId>junits</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
JUnits can be used using dependency tag in
maven in pom.xml. The version as desired and
A available in repository can be used.
class Output
{ 257
public static void main(String args[])
{
What willInteger i = new
be the Integer(257);
output of the following Java program?
byte x = i.byteValue();
What will be the output
System.out.print(x); of the following Java program
final
class}class A
main_class
{ 22
}{ int i;
} public static void main(String args[])
class{ B extends A
{ int x = 9;
int j;if (x == 9)
System.out.println(j
{ + " " + i); Server
}
Which classint x = 8; system independent server side implementation?
provides
class inheritance
System.out.println(x);
{ }
public
} static void main(String args[]) 9
{
} B obj = new B();
obj.display();
}
}
}
class Foundry extends San
{
Foundry()
{
}
public static void main(String[]args)
{
}
} compile ti
What will be the output of the following Java code?
class box
{
int width;
int height;
int length;
int volume;
void finalize()
{
volume = width*height*length;
System.out.println(volume);
}
protected void volume() 150
{
volume = width*height*length;
System.out.println(volume);
}
}
class Output
{
public static void main(String args[])
{
box obj = new box();
obj.width=5;
obj.height=5;
obj.length=6;
obj.volume();
}
}
What will be the output of the following Java code?
class area
{
int width;
int length;
int area;
void area(int width, int length)
{
this.width = width;
this.length = length; 00
}
}
class Output
{
public static void main(String args[])
{
area obj = new area();
obj.area(5 , 6);
System.out.println(obj.length + " " + obj.width);
}
}
class box
{
int width;
int height;
int length;
int volume;
void volume()
{
volume = width * height * length; 0
}
void volume(int x)
{
volume = x;
}
}
class Output
{
public static void main(String args[])
{
box obj = new box();
obj.height = 1;
obj.length = 5;
obj.width = 5;
obj.volume(5);
System.out.println(obj.volume);
}
}
class Output
{
static void main(String args[]) 1
{
int x , y = 1;
x = 10;
if(x != 10 && x / 0 == 0)
System.out.println(y);
else
System.out.println(++y);
}
}
What will be the output of the following Java program?
class area
{
int width;
int length;
int height;
area()
{ 0
width = 5;
length = 6;
height = 1;
}
void volume()
{
volume = width * height * length;
}
}
class cons_method
{
public static void main(String args[])
{
area obj = new area();
obj.volume();
System.out.println(obj.volume);
}
}
What will be the output of the following Java snippet, if attempted to compile and run this code
with command line argument “java abc Rakesh Sharma”?
public class abc
{
int a=2000;
public static void main(String argv[])
{
System.out.println(argv[1]+" :-Please pay Rs."+a);
}
} Compile time error
What will be the output of the following Java program?
final class A
{
int i;
}
class B extends A 22
What { will be the output of the following Java program?
classintAj;
{ System.out.println(j + " " + i);
} int i;
class inheritance
public void display()
{ {
public static void main(String args[])
System.out.println(i);
{}
B obj = new B();
} obj.display();
class
} B extends A
{}
int j;
public void display()
{
What willSystem.out.println(j);
be the output of the following Java program?
class Abc }
{}
publicDynamic_dispatch
class static void main(String[]args)
{ {
String[] elements = { "for", "tea", "too" };
public static
String first void main(String> args[])
= (elements.length 0) ? elements[0]: null;
} {
} B obj2 = new B(); Compilatio
obj2.i = 1;
obj2.j = 2;
A r;
r = obj2; 1
r.display();
}
}
What will be the output of the following Java code?
class exception_handling
{
public static void main(String args[])
{
try
{
int a = args.length; 0
int b = 10 / a;
System.out.print(a);
}
catch (ArithmeticException e)
{
System.out.println("1");
}
}
}
class exception_handling
{
public static void main(String args[])
{ A
try
{
throw new NullPointerException ("Hello");
}
catch(ArithmeticException e)
{
System.out.print("B");
}
}
}
What will be the output of the following Java code?
class exception_handling
{
public static void main(String args[])
{
try
{
int a = 1;
int b = 10 / a;
try
{
if (a == 1) A
a = a / a - a;
if (a == 2)
{
int c[] = {1};
c[8] = 9;
}
}
finally
{
System.out.print("A");
}
}
catch (Exception e)
{
System.out.println("B");
}
}
}
What will be the output of the following Java code?
class exception_handling
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 10 / a;
System.out.print(a);
try
{
if (a == 1)
a = a / a - a;
if (a == 2)
{
int []c = {1};
c[8] = 9;
}
}
catch (ArrayIndexOutOfBoundException e)
{
System.out.println("TypeA");
}
catch (ArithmeticException e)
{
System.out.println("TypeB");
}
}
} TypeA
Option B Option C Option D Answer Explanation
67 65 64 A
1 1 0 C
1 1 0 D
65 97 67 95 66 98 B
None of the
120 0 A
mentioned
1 0 1
1 25 26 C
only sum(1only sum(10) & sum(10,20D sum is a variable argument method and hence it can take any numb
1 30 Error D
run time ercompile and unreported exc If parent class constructor throws any checked exception, compulsor
200 Runtime Error
Compilation Error A
56 65 55 C
this keyword can be used inside any method to refer to the current o
float int m compile timerun time error While resolving overloaded method, compiler automatically promotes
6 7 8 C
7 8 9 C
6.4 6.4 6.4 6 4 6.4 D
Variables a & b are passed by value, copy of their values are made
20 10 20 40 40 20 B
33 Runtime Error
Compilation Error B
6 6.4 79 97 C
23 32 15 D
11 22 Compilation Error C
All objects of class share same static variable, all the objects share s
C
66 79 97
123 1234 12345 arr.length() is 5, so the loop is executed for three times
L K E A
10 11 12 C
true true true false false true equals() is method of class String, it is used to check equality of two
1 6 25 C
1 0 1 B
5 25 26 B
2 Runtime Error
Compilation Error D
main() method must be made public. Without main() being public jav
1 25 30 D
CompilatioCompilation Compilation a Main method is static and cannot access non static variable a.
33 Runtime Error
Compilation Error D
An exceptio
The variable The
f variable fi The value at the 0th position will be assigned to the variable first.
2 3 4 B
B Compilation ErorRuntimeError D
The inner try block does not have a catch which can tackle ArrayInde
C
piler automatically promotes if exact match is not found. But in this case, which one to promote is an ambiguity.
mber 4 gets executed and value of x is 4. For the next function call, the function in line number 7 gets executed and value of y is
py of their values are made on formal parameters of function meth() that is i & j. Therefore changes done on i & j are not reflect
rence, therefore changes done are reflected back on original arguments. obj.meth(obj) sends object obj as parameter whose va
iable, all the objects share same copy of static members, obj1.x and obj2.x refer to same element of class which has been incr
or three times
s, they contain an attribute that is length which contains the number of elements that can be stored in the array. Hence a1.leng
concatenate strings.
h gives the character specified by the index. obj.charAt(3) gives 4th character i:e I
sed to check equality of two String objects, if they are equal, true is retuned else false.
hout main() being public java run time system will not be able to access main() and will not be able to execute the code.
non static variable a.
cannot be inherited by any other class. Hence class B does not have member i, giving compilation error.
signs a reference of object obj2 to r and uses that reference to call function display() of class B.
n but the catch block is used to counter Arithmetic Exception. Hence NullPointerException occurs since no catch is there which
h which can tackle ArrayIndexOutOfBoundException hence finally is executed which prints ‘A’ the outer try block does have cat
s parent, otherwise code won’t compile.
n ambiguity.
s executed and value of y is 6.4
done on i & j are not reflected back on original arguments. a & b remain 10 & 20 respectively.
obj as parameter whose variables a & b are multiplied and divided by 2 respectively by meth() function of class test. a & b bec
f class which has been incremented twice and its value is 2.
in the array. Hence a1.length gives 10 and a2.length gives 5.
to execute the code.
ince no catch is there which can handle it, runtime error occurs.
uter try block does have catch for ArrayIndexOutOfBoundException exception but no such exception occurs in it hence its catch
tion of class test. a & b becomes 20 & 10 respectively.
n occurs in it hence its catch is never executed and only ‘A’ is printed.