Вы находитесь на странице: 1из 468

MCQS

Predict the output

char ‘ data types holds a single character from the.................. character


set.

a) ASCII Code
b)Unicode
c) Both (a) & (b)
d) None of these
Predict the output
class mainclass
{ a) 0
public static void main(String args[])
{ b) 1
boolean var1 = true;
c) true
boolean var2 = false;
if (var1) d) false
System.out.println(var1);
else
System.out.println(var2);
}
}
Predict the output
class booloperators a) 0
{
b) 1
public static void main(String args[])
{ c) true
boolean var1 = true;
boolean var2 = false; d) false
System.out.println((var1 & var2));
}
}
Predict the output
class asciicodes
a) 162
{
public static void main(String args[]) b) 65 97
{ c) 67 95
char var1 = 'A';
d) 66 98
char var2 = 'a';
System.out.println((int)var1 + " " + (int)var2);
}
}
Predict the output
class A{ A. 258 325 325
public static void main(String args[]){ B. 258 326 326
byte b;
C. 2 325 69
int i = 258;
double d = 325.59; D. Error
b = (byte) i;
System.out.print(b);
i = (int) d;
System.out.print(i);
b = (byte) d;
System.out.print(b);
}}
class A
Predict the output
{ A. 10 20 10 100
public static void main(String args[])
B. 10 20 10 20
{
int x; C. 10 20 10 10
x = 10;
if(x == 10) D. Error
{
int y = 20;
System.out.print("x and y: "+ x + " " + y);
y = x*2;
}
y = 100;
System.out.print("x and y: " + x + " " + y);
}
}
Predict the output
public class Test
{
static void test(float x) A. float
{
System.out.print("float"); B. double
}
static void test(double x) C. Compilation Error
{
System.out.print("double"); D. Exception is thrown at runtime
}
public static void main(String[] args)
{
test(99.9);
}
}
Predict the output
public class Test
A. 8 7
{
B. 10 7
public static void main(String[] args)
C. Compilation fails with an error
{
at line 3
int i = 010;
D. Compilation fails with an error
int j = 07; at line 5
System.out.println(i); E. None of these
System.out.println(j);
}
}
Predict the output
public class MyClass
(A) 10
{
public static void main(String[] args) (B) 11
{ (C) 12
int a = 10;
(D) Compilation Error
System.out.println(++a++);
}
}
Predict the output
public class Main
(A) 138
{
public static void main(String[] args) (B) 264
{ (C) 41
int a = 5+5*2+2*2+(2*3);
(D) 25
System.out.println(a);
}
}
Predict the output

What do you mean by >>> operator in Java?


A) Left Shift Operator
B) Right Shift Operator
C) Zero Fill Right Shift
D) Zero Fill Left Shift
Predict the output
class char_increment a) E U
{
public static void main(String args[]) b) U E
{
char c1 = 'D'; c) V E
char c2 = 84;
d) U F
c2++;
c1++;
System.out.println(c1 + " " + c2);
}
}
Predict the output
class c
a) Hello c
{
public void main( String[] args ) b) Hello
{ c) Hello world
System.out.println( "Hello" + args[0] );
d) Runtime Error
}
}
Predict the output
class increment
a) 25
{
b) 24
public static void main(String args[])
{ c) 32
int g = 3; d) 33
System.out.print(++g * 8);
}
}
class array_output
Predict the output
{
public static void main(String args[]) a) i i i i i
{ b) 0 1 2 3 4
char array_variable [] = new char[10];
c) i j k l m
for (int i = 0; i < 10; ++i)
{ d) None of the mentioned
array_variable[i] = 'i';
System.out.print(array_variable[i] + "" );
i++;
}
}
}
Predict the output
class mainclass a)66
{
public static void main(String args[]) b)67
{ c)65
char a = 'A';
a++; d)64
System.out.print((int)a);
}
}
Predict the output
class conversion a) 38 43
{
public static void main(String args[]) b) 39 44
{
c) 295 300
double a = 295.04;
int b = 300; d) 295.04 300
byte c = (byte) a;
byte d = (byte) b;
System.out.println(c + " " + d);
}
}
class variable_scope Predict the output
{
public static void main(String args[]) a) 5 6 5 6
{
b) 5 6 5
int x;
x = 5; c) Runtime error
{
d) Compilation error
int y = 6;
System.out.print(x + " " + y);
}
System.out.println(x + " " + y);
}
}
Predict the output
class dynamic_initialization
{
public static void main(String args[]) a) 5.0
{
double a, b; b) 5
a = 3.0;
c) 7
b = 4.0;
double c = Math.sqrt(a * a + b * b); d) Compilation Error
System.out.println(c);
}
}
Predict the output
import java.lang.Math;
class dynamic_initialization
{
public static void main(String args[]) a) 5.0
{
double a, b; b) 5
a = 3.0;
c) 7
b = 4.0;
double c = Math.sqrt(a * a + b * b); d) Compilation Error
System.out.println(c);
}
}
Predict the output
class output a) Infinity
{
public static void main(String args[]) b) 0.0

{
c) NaN
double a, b,c;
a = 3.0/0; d) all of the mentioned
b = 0/4.0;
c=0/0.0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Thank You
Basic I/O
Which of these data types is used to store command line arguments?

a. Array

b. Stack

c. String

d. Integer
Basic I/O
class Test
{
public static void main(String[] args)
{
for(int i = 0; 1; i++) Output: Error
{
System.out.println("Hello");
break;
}
}
}
Basic I/O
Can command line arguments be converted into int automatically if required?

a. Yes

b. No

c. Compiler dependent

d. Only ASCII can be converted


Basic I/O
Which is the correct declaration of a boolean variable?

a. boolean check=‘false’;

b. boolean check=0;

c. boolean check=“false”

d. boolean check=false
Basic I/O

Write a program to get a input from user and print it using command
line arguments
Basic I/O
What is the output of this program, Command line execution is done
as “java output This is a command Line”?

class Output
{
public static void main(String args[])
{ Output: This
System.out.print(args[0]);
}
}
Basic I/O
What is the output of this program, Command line execution is done
as “java output This is a command Line”?

class Output
{
public static void main(String args[])
{ Output: command
System.out.print(args[3]);
}
}
Basic I/O
What is the output of this program, Command line execution is done
as “java output This is a command Line”?

class Output
{
public static void main(String args[])
{ Output:
System.out.print(args); java.lang.String;@3c679bde
}
}
Basic I/O

Write a program to get a input from user add 2 numbers and print the
result using command line arguments
Basic I/O
What is the output of this program

public class prg a. -1


{
public static void main(String[] args) b. 255
{
System.out.println( (byte) 0xff);
}
c. 65535
}
d. 0xff
Basic I/O
What are scanners in Java programming language?

It enables splitting of string and primitive data into separate tokens,


based on a delimiter that can be a regular expression
Basic I/O

Write a program to get a input from user and swap 2 numbers using
command line arguments
Basic I/O

Write a program to get a input from user and swap 2 numbers without
using third variable using command line arguments
Basic I/O
What are the I/O streams Java programming language?

Input sources from which data is read, and output destinations to


which data is written

Streams support different kinds of data including bytes, characters,


primitive types and objects
Basic I/O
What should be the name of java program file containing this
program?
a. MyPrg.class
class MyPrg
{
b. MyPrg.java
public static void main(String args[])
{
System.out.print("IncludeHelp"); c. MyPrg
}
} d. Any file name
with java extension
Basic I/O
What should be the name of java program file containing this
program?
a. MyPrg.class
public class MyPrg
{
b. MyPrg.java
public static void main(String args[])
{
System.out.print("IncludeHelp"); c. MyPrg
}
} d. Any file name
with java extension
Basic I/O
What is the output of this program

public class Prg a. ABA


{
public static void main(String args[])
b. AB65
{
System.out.print("A" + "B" + 'A');
} c. error
}
d. AB
Mcqs
Predict the output
class Main a) Compile time error
{ b) Garbage value
public static void main(String args[]) c) 0
{ d) Run time error
int t;
System.out.print(t);
}
}
Predict the output
class Program a) Compile time error
{ b) Garbage value
int i; c) 0
} d) Run time error
class Main
{
public static void main(String args[])
{
Program p;
System.out.println(p.i);
}
}
Predict the output
class Program a) Compile time error
{ b) Garbage value
int i; c) 0
} d) Run time error
class Main
{
public static void main(String args[])
{
Program p = new Program();
System.out.println(p.i);
}
}
Predict the output
Which of these class is superclass of every class in Java?

a) String class
b) Object class
c) Abstract class
d) ArrayList class
Predict the output
Which of the following is not a valid declaration of a Top level class ?

a) final public class Program {}


b) class $Test {}
c) static class Test {}
d) public class Test {}
Predict the output
Which statement does not create an object of class Student{} ?

a) new Student();
b) Student s = new Student();
c) Student s;
d) Student s1 = new Student(), s2 = new Student();
Predict the output
this keyword in java is used to ?

a) refer to current class object


b) refer to static method of the class
c) refer to parent class object
d) refer to static variable of the class
Predict the output
What is the prototype of the default constructor for given class?
public class Test { }

a) Test()
b) public Test()
c) Test (void)
d) public Test(void)
Predict the output
Which method is called by Garbage collection thread just before collecting
eligible Objects ?

a) finally()
b) finalize()
c) final()
d) gc()
Predict the output
Garbage Collection in java is done by whom?

a) Java Compiler
b) Object class
c) JVM
d) System class
class B
Predict the output
{
static int count = 100; a) 100
public void increment()
{ b) 101
count++;
c) Error in line 13
}
public static void main(String []args) d) 0
{
B b1 = new B();
b1.increment();
B b2 = new B();
System.out.println(b2.count); // line 13
}
}
Predict the output
Which of the following statement declares a constant field in Java?

a) const int x = 10;


b) static int x = 10;
c) final static int x = 10;
d) volatile int x =10;
Predict the output
Given the following code, which line will generate an error ?
class Test
• Line 3
{
• Line 4
static int x = 100; // line 3
• Line 7
int y = 200; // line 4
• Line 8
public static void main(String []args)
{
final int z; // line 7
z = x + y; // line 8
System.out.println(z);
}
}
Predict the output
What will happen if you try to compile and run the following
code ?
class Test a) Program exits without printing
{ anything
int x; b) Compilation error at line 10
Test(int n) c) Compilation error at line 6
{ d) Run-time exception
System.out.println(x=n); // line 6
}

public static void main(String []args)


{
Test n = new Test(); // line 10
}
}
Predict the output
super keyword in Java is used for?

a) to refer to immediate child class of a class


b) to refer to immediate parent class of a class
c) to refer to current class object
d) to refer to static member of parent class
Predict the output
Multiple inheritance is not supported in Java because?

a) To remove ambiguity and provide more maintainable and clear design


b) Java is a Object oriented language.
c) Multiple inheritance is not an important feature.
d) All of above
public class Test Predict the output
{
public static void left(int i, int j) a) 2
{ b) 4
i <<= j; c) 8
} d) 16
public static void main(String args[])
{
int i = 4, j = 2;
left(i,j);
System.out.prinln(i);
}
}
Predict the output
class bitwise_operator
{ a) 42 42
public static void main(String args[]) b) 43 43
{ c) 42 -43
int var1 = 42; d) 42 43
int var2 = ~var1;
System.out.prin(var1+” “+var2);
}
}
Predict the output
class operators
a) 24, 8
{
b) 24, 9
public static void main(String args[])
c) 27, 8
{
d) 27, 9
int x = 8;
System.out.print(++x * 3+”, ”+x);
}
}
Predict the output
class Test
{
protected int x, y;
} Output:
00
class Main
{
public static void main(String args[])
{
Test t = new Test();
System.out.println(t.x + " " + t.y);
}
}
Predict the output
class Main
{
public static void main(String args[])
{
System.out.println(fun());
} a) Compilation error
b) 20
int fun() {
c) Runtime error
return 20; d) None of these
}
}
Predict the output
class Test
{
public static void main(String args[])
{
System.out.println(fun());
} a) Compilation error
static int fun() { b) 1
static int x= 0; c) Runtime error
return ++x; d) None of these
}
}
Predict the output
public class Calculator
{
int num = 100;
public void calc(int num) { this.num = num * 10; }
public void printNum() { System.out.println(num); }
a) 100
public static void main(String[] args) b) 1000
c) 20
{ d) None of these
Calculator obj = new Calculator();
obj.calc(2); obj.printNum(); }
}
Predict the output
class Test2
class Test1 {
{ Test1 t1 = new Test1(10);
Test1(int x) Test2(int i)
{ {
System.out.println("Constructor t1 = new Test1(i);
called " + x); }
} public static void main(String[] args)
} {
Test2 t2 = new Test2(5);
}
}
Predict the output
class GfG
{
public static void main(String args[])
{
String s1 = new String(“GOOD");
String s2 = new String(“GOOD");
if (s1 == s2)
System.out.println("Equal"); a) Compilation error
else b) Equal
System.out.println("Not equal"); c) Not Equal
} d) None of these
}
What is the output of the following program?
public class Test
{ a) 677
public static void main(String[] args) b) Compilation error due to line 1
{ c) Compilation error due to line 2
int value = 554; d) Compilation error due to line 1 and
String var = (String)value; //line 1 line 2
String temp = "123";
int data = (int)temp; //line 2
System.out.println(data + var);
}
}
Predict the answer
Which of the following is/are true about constructors in Java?
1)Constructor name should be same as class name.
2) If you don't define a constructor for a class, a default parameterless
constructor is automatically created by the compiler.
3) The default constructor calls super() and initializes all instance variables to
default value like 0, null.
4) If we want to call parent class constructor, it must be called in first line of
constructor.
a) 1
b) 1,2
c) 1,2,3
d) 1,2,3,4
Predict the output
class Complex {
private double re, im;
public String toString() { return "(" + re + " + " + im + "i)"; }
Complex(Complex c) { re = c.re; im = c.im; }
}
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(); Complex c2 = new Complex(c1);
System.out.println(c2); a) Compilation error
} b) 0.0+0.0i
c) Runtime error
} d) None of these
What is the output of the following program
class Helper
{
private int data;
private Helper() { data = 5; }
a) Compilation error
}
b) 5
public class Test c) Runtime error
{ public static void main(String[] args) d) None of these
{ Helper help = new Helper();
System.out.println(help.data);
}}
Predict the answer
class Temp
{ private Temp(int data) {
a) Constructor called Method called
System.out.printf(" Constructor called "); } b) Compilation error
protected static Temp create(int data) { c) Runtime error
d) None of the above
Temp obj = new Temp(data); return obj; }
public void myMethod()
{ System.out.printf(" Method called "); }
}
public class Test
{ public static void main(String[] args)
{ Temp obj = Temp.create(20); obj.myMethod(); }
}
Predict the answer
public class Test
{ public Test(int data, int temp)
public Test() {
{ System.out.printf("3");
System.out.printf("1"); }
new Test(10); public static void main(String[] args)
System.out.printf("5"); {
} Test obj = new Test();
public Test(int temp)
}
{ a) 12345
}
System.out.printf("2"); b) Compilation error
new Test(10, 20); c) 15
System.out.printf("4"); d) Runtime error
}
THANK YOU
CHOOSE THE CORRECT ANSWER
What is the valid data type for variable “a” to print “Hello
World”?
switch(a)
{
System.out.println(“hello world”);
}
a. int and float
b. byte and short
c. char and long
d. byte and char
CHOOSE THE CORRECT ANSWER
Which of the following is not a valid jump statement?
a. Break
b. Goto
c. Continue
d. return
CHOOSE THE CORRECT ANSWER

From where break statement causes an exit?


a. Only from innermost loop
b. Terminates a program
c. Terminates a program
d. From innermost loops or switches
CHOOSE THE CORRECT ANSWER
Which of the following is not a valid flow control
statement?
a. exit()
b. Break
c. Continue
d. return
PREDICT THE OUTPUT
class Test
{
public static void main(String[] args)
{
int i = 0, j = 9; a. 44
do
{
i++;
b. 55
if (j-- < i++)
{
c. 66
break;
}
d. 77
} while (i < 5);
System.out.println(i + "" + j);
}
}
PREDICT THE OUTPUT
What will be the output of the following program?
a. 000 class Test
b. 222 {
public static void main(String[] args)
c. 333 {
int j = 0;
d. error do
for (int i = 0; i < 1; i++)
System.out.println(i);
while (j++ < 2);
}
}
class Test
PREDICT THE OUTPUT
{
static String s = "";
public static void main(String[] args)
{ a. 32
P:
for (int i = 2; i < 7; i++) b. 23
{
if (i == 3) c. 24
continue;
if (i == 5) d. 42
break P;
s = s + i;
}
System.out.println(s);
}
}
class Test
PREDICT THE OUTPUT
{
public static void main(String[] args)
{
int x = 10;
if (++x < 10 && (x / 0 > 10))
a. Compile time error
{
System.out.println("Bishal"); b. RuntimeException
} c. Bishal
else
d. GEEKS
{
System.out.println("GEEKS");
}
}
}
PREDICT THE OUTPUT
class Test
{
public static void main(String[] args) a. Compile time error
{
final int a = 10, b = 20;
b. GEEKS
while (a > b)
{
System.out.println("Hello"); c. Hello
}
System.out.println("GEEKS");
} d. No Output
}
PREDICT THE OUTPUT
class Test
{
public static void main(String[] args)
{ a. HELLO
boolean b = true;
if (b = false) b. BYE
{ c. Compile time error: re- initializatio
System.out.println("HELLO"); d. No Output
}
else
{
System.out.println("BYE");
}
}
}
PREDICT THE OUTPUT

class Test
{
public static void main(String[] args) a. HELLO
{ b. HELLO (Infinitely)
do c. Error: Unreachable statement
while (true); d. Error: ; expected
System.out.println("HELLO");
}
}
PREDICT THE OUTPUT
class Test
{
public static void main(String[] args)
{
do a. 12
{ b. 21
System.out.print(1);
do
c. 1
{ d. 2
System.out.print(2);
} while (false);
} while (false);
}
}
PREDICT THE OUTPUT
public class Test
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) a. No Output
int x = 10; b. 10
}
} c. Compile time error
d. 10 (10 times)
PREDICT THE OUTPUT
public class Test
{ a. HELLO GEEKS
public static void main(String[] args) b. Compile time error
{ c. HELLO GEEKS
for (int i = 0, String = "GFG"; i < 2; i++) HELLO GEEKS
System.out.println("HELLO GEEKS"); HELLO GEEKS
} d. No Output
}
PREDICT THE OUTPUT
public class Test
{
public static void main(String[] args)
{ a. HI
int i = 0; HELLO GEEKS
for (System.out.println("HI"); i < 1; i++) b. No Output
System.out.println("HELLO GEEKS");
c. Compile time error
}
} d. HELLO GEEKS
public class Test PREDICT THE OUTPUT
{
public static void main(String[] args)
{
for (int i = 0; i < 1; System.out.println("WELCOME"))
System.out.println("GEEKS");
}
} a. GEEKS
WELCOME
b. No Output
c. Compile time error
d. GEEKS WELCOME(Infinitely)
class Test
PREDICT THE OUTPUT
{
public static void main(String args[])
{
int x = 7;
if(x == 2);
System.out.println(“NumberSeven”);
System.out.println(“NotSeven”); a. NumberSeven NotSeven
} b. NumberSeven
} c. NotSeven
d. Compilation Error
e. 7
PREDICT THE OUTPUT
public class Test
{
public static void main(String args[])
{
int i = 1; a. 1
do
{ b. 2
i--; c. -1
}
while(i > 2); d. 0
System.out.println(i);
}
}
PREDICT THE OUTPUT
int i = 10;
while(i++ <= 10) a. 10
{ b. 11
i++; c. 12
d. 13
}
e. Line 5 will never be reached
System.out.print(i);
CHOOSE THE CORRECT ANSWER
In java, ............ can only test for equality, where as
.......... can evaluate any type of the Boolean expression.
a. switch, if
b. if, switch
c. if, break
d. continue, if
Array - MCQ’S
Predict the output
In Java arrays are ?

A. Objects
B. Object Reference
C. Primitive Data type
D. None
Predict the output
What is the result of compiling and running the following code?
public class test
{
public static void main(string args[])
{
int [] a = new int[0];
System.out.println(a.length);
}
}
A. 0
B. Compilation error, arrays can not be initialized to size 0
C. Compilation error, it is a.length() and not a.length.
D. None
Predict the output
What is the result of compiling and running the following code?
public class Test
{
public static void main(String args[])
{
int [] a = new int[3];
System.out.println("a[0] is"+a[0]);
}
}
A. Compilation error size of array is must during declaration.
B. Comilation error,array ellements not initialized.
C. Program runs fine output is a[0] is 0
D. Run time error as the a[0] is not defined
Predict the output
What is the result of compiling and running the following code?
public class Test
{
public static void main(String args[])
{
int [] a = {120,200,016};
for(int i = 0; i<a.length ; i++)
System.out.print(a[i]);
}
}
A. 120 200 16
B. 120 200 14
C. 120 200 016
D. Compilation Error
Predict the output
When you pass an array to a method, the method recieves _________ ?
A. A copy of the array
B. A copy of first element
C. The reference of the array
D. The length of the array
Predict the output
What is the value of a[1] after the following code executed?

Int a[] = {0,2,4,1,3};


for(int i = 0; i<a.length; i++)
a[i] = a[(a[i]+3)%a.length];

A. 0
B. 1
C. 2
D. 3
Predict the output
Output of following Java program?
class Test
{
public static void main (String[] args) A. Same
{ B. Not same
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3}; C. Compilation error
if (arr1 == arr2) D. Run time error
System.out.println("Same");
else
System.out.println("Not same");
}
}
Predict the output
import java.util.*;
class Array
{
public static void main(String args[])
{ A. 12345
int array[] = new int [5]; B. 54321
for (int i = 5; i > 0; i--)
array[5 - i] = i; C. 1234
Arrays.sort(array); D. 5432
for (int i = 0; i < 5; ++i)
System.out.print(array[i]);;
}
}
What is the output?
class Sample
Predict the output
{
public static void main(String args[])
{
int[] x = {5,6,7,8,9};
int[] y = x;
y[2] = 10;
System.out.println(x[2]);
System.out.println(y[2]);

}
}
A. 10
10
B. 7
10
C. Compile Time error
D. None of the Above
Predict the output
Guess the output.
class Sample
{
public static void main(String args[])
{
int[] x = {5,6,7,8,9};
int[] y = x;
if(x==y)
System.out.println(x[2]);
else
System.out.println(x[0]);

}
} Output: 7
Predict the output
class Sample
{
public static void main(String args[])
{
int[] x = {5,6,7,8,9};
int y = x;
System.out.println(y);
}
}
A. 5
B. Compile time error
C. Address of x
D. None
Predict the output
Which are valid ways to declare a 2D Array?

int a[][];

int [][]a;

int []a[];
Predict the output
What is the output ?
public static void main(String args[])
{
int x[]={1,2,3,4,5},[]y={5,4,3,2,1},i;
for(i=0;i<4;i++)
x[i]=y[i];
System.out.println(x[i]+y[i]);
}

A. 1
B. 6
C. Compilation error
D. Runtime Error
Predict the output
You want to create a table that looks like:
A. double[][] table = { 12, -9, 8,
7, 14,
12 -9 8 -32, -1, 0} ;

7 14 B. double[][] table = { {12, -9, 8},


{7, 14, 0},
-32 -1 0 {-32, -1, 0} };

C. double[][] table = { {12, -9, 8}


{7, 14}
-32, -1, 0} };
D. double[][] table = { {12, -9, 8},
{7, 14},
{-32, -1, 0} };
Predict the output
Given the following:

double[][] things ={ {1.2, 9.0},


{9.2, 0.5, 0.0},
{7.3, 7.9, 1.2, 3.9} } ;
What is the value of things[2].length ?
A. 2
B. 3
C. 4
D. 9
Predict the output
Which of the following statements correctly declares a two-dimensional integer array?
(A) int Matrix[ ] = new int[5,4];
(B) int Matrix[ ]; Matrix = new int[5,4];
(C) int Matrix[ ][ ] = new int[5][4];
(D) int Matrix[ ][ ]; Matrix = new int[5][4];
(E) Both choices C and D
Predict the output
What will be printed by the following program statement?
System.out.println(matrix[0].length);
(A) The number of rows in a two-dimensional "square" static array.
(B) The number of columns in a two-dimensional "non-ragged" array.
(C) The number of columns in the top row of a two-dimensional static array.
(D) The number of columns in the row with index[0] of a two-dimensional array.
(E) All of the above
Predict the output
Consider the following two-dimensional array declaration. int[][] matrix = new int[4][4]; Which of
the following statements will assign the correct size to rowSize?
(A) int rowSize = matrix.length;
(B) int rowSize = matrix[0].length;
(C) int rowSize = matrix[1].length;
(D) int rowSize = matrix[2].length;
(E) All of the above
Predict the output
Consider the mambo object declaration below.
double mambo[ ][ ];
mambo = new double[4][5];
int r; // row index on mambo
int c; // column index of mambo
Which of the following statements stores the row length of mambo?
(A) mambo.length
(B) mambo.rowLength
(C) mambo[r].length
(D) mambo[c].length
Predict the output
Predict the Output: for(i=n;i>0;i--)
class Array {
{ System.out.println("a["+i+"] = "+ a[i]);
public static void main(String args[]) }
{ }
int i,n; }
Runtime Error:
Scanner s = new Scanner(System.in);
n=s.nextInt(); ArrayOutOfBoundException
int []a = new int[n];
for(i=0;i<n;i++) INPUT: 5
{
12345
a[i]=s.nextInt();
} OUTPUT :

54321
Thank you
STRINGS
1. What is the output of the following snippet? a) Compilation Error
class Strings
{ b) FACE
public static void main(String[] args){ c) Focus
String str1 = new String("FACE");
d) Throws exception
String str2 = new String("Focus");
System.out.print(str1 = str2);
}
}
STRINGS
2. What is the output of the following snippet? a) True
class Strings
{ b) False
public static void main(String[] args){ c) Compilation error
String str1 = "FACE";
d) ClassCast Exception at Runtime
StringBuffer str2 = new StringBuffer(str1);
System.out.print(str1.equals(str2);
}
}
STRINGS
3. What is the output of the following snippet? a) Java3Quiz34
class Strings
{ b) Java12Quiz34
public static void main(String[] args){ c) Java3Quiz7
String s = "Java"+1+2+"Quiz"+""+(3+4);
d) Java12Quiz7
System.out.println(s);
}
}
STRINGS
4. What is the output of the following snippet? a) -3
class Strings
{ b) 0
public static void main(String[] args){ c) true
String s1 = "abc";
d) false
String s2 = "def";
System.out.println(s1.compareTo(s2));
}
}
STRINGS
5. What is the output of the following snippet? a) Null
class Strings
{ b) abcabc
public static void main(String[] args){ c) abc
String x = "abc";
d) Compilation error
String y = "abc";
x.concat(y);
System.out.print(x);
}
}
STRINGS
6. How many objects were created in the below snippet? a) 1
class Strings
{ b) 2
public static void main(String[] args){ c) 3
String s = “FACE";
d) 4
String s1 = new String(“Focus");
}
}
STRINGS
7. What is the output of the following snippet? a) true
class Strings
b) str1 == str2 is : true
{
public static void main(String[] args){ c) str1 == str2 is : false
String str1 = “FACE";
d) false
String str2 = “FACE";
System.out.println("str1 == str2 is:"+str1==str2);
}
}
STRINGS
8. Which of the below mentioned implementation pattern would string implementation follow?

a) Factory Pattern

b) Singleton Pattern

c) Flyweight Design Pattern

d) None of these
STRINGS
9. What is the output of the following snippet? a) true
class Strings
b) null
{
public static void main(String[] args){ c) false
String str1 = “FACE"; d) Compilation error
String str2 = new String(“FACE");
s2.intern();
System.out.println(str1==str2);
}
}
STRINGS
10. What is the output of the following snippet? a) true false
class Strings
b) true true
{
public static void main(String[] args){ c) false true
String str2 = "FACE"; d) false false
String str3 = new String("FACE");
String str1 = "FACE";
System.out.print(str1==str2);
System.out.print(str1==str3);
}
}
STRINGS
11. What is the output of the following snippet? a) Compile Time Error
class Strings
b) Runtime Exception
{
public static void main(String[] args){ StringIndexOutOfBoundsException
String str = "Focus Academy For Career
c) Prints "Str"
Enhancement private limited";
System.out.println(str.substring(5,3)); d) Runtime Exception
}
IndexOutOfBoundsException
}
STRINGS
12. What is the output of the following snippet? a) Prints “e”
class Strings
b) Runtime Exception
{
public static void main(String[] args){ c) Prints “E"
String str = “FACE Academy face";
d) Converts “E” to 69 and prints 69
System.out.println(str.charAt(str.toUpperCase().
length()));
}
}
STRINGS
13. What is the output of the following snippet? a) NullPointerException
class Strings
NullPointerException
{
public static void main(String[] args){ b) null NullPointerException
String str1 = null;
System.out.println(str1); c) null null
System.out.println(str1.toString()); d) Compilation error
}
}
STRINGS
14. What is the output of the following snippet? a) truetrue
class Strings
b) falsefalse
{
public static void main(String[] args){ c) truefalse
String str1 = “FACE";
String str2 = new String(“FACE"); d) falsetrue
System.out.print(str1==str2);
System.out.println(str1==str2.intern());
}
}
STRINGS
15. Where is toString method defined?

a) String class

b) Object class

c) StringBuffered class

d) None of these
STRINGS
16. Which of these methods is used to compare a specific region inside a string with another
specific region in another string?

a) regionMatch()

b) match()

c) regionMatches()

d) RegionMatches()
STRINGS
17. Which of these method of class String is used to check weather a given object starts with a
particular string literal?

a) startsWith()

b) Starts()

c) endsWith()

d) ends()
STRINGS
18. What is the string contained in str after following lines of code? a) Hell
class Strings
b) ello
{
public static void main(String[] args){ c) Hel
StringBuffer str = new StringBuffer(“Hello”);
str.deleteCharAt(0); d) llo
}
}
STRINGS
19. Which of the following are incorrect form of StringBuffer class constructor?

a) StringBuffer()

b) StringBuffer(int size)

c) StringBuffer(String str)

d) StringBuffer(int size , String str)


STRINGS
20. String constant pool allocates its memory in

a) Stack

b) Heap

c) Data Segment

d) Register
STRINGS
21. To overcome immutable nature of string class we use

a) StringBuffer

b) StringBuilder

c) Both a and b

d) None of these
STRINGS
22. Which class will you recommend among String, StringBuffer and StringBuilder classes if I want
mutable and thread safe objects?

a) String

b) StringBuffer

c) StringBuilder

d) None of these
Predict
1) Below class ABC doesn’t have even a single abstract method, but it has been declared as

abstract. Is it correct?

abstract class ABC


{
void firstMethod()
{
System.out.println("First Method");
}
void secondMethod()
{
System.out.println("Second Method");
}
}
 Yes, it is correct. abstract classes may or may not have abstract methods.1
Abstract Class
2. Which of the following is FALSE about abstract classes in Java

(A) If we derive an abstract class and do not implement all the abstract methods, then the

derived class should also be marked as abstract using ‘abstract’ keyword

(B) Abstract classes can have constructors

(C) A class can be made abstract without any abstract method

(D) A class can inherit from multiple abstract classes.

2
Abstract Class
3.Why the below class is showing compilation error?
abstract class AbstractClass
{
abstract void abstractMethod()
{
System.out.println("First Method");
}
}

Because, abstract methods must not have a body.


3
Abstract Class
4.Which class is instantiable? Class A or Class B?
abstract class A
{
}
class B extends A
{
}

Class B.
4
Abstract Class
5. Below code snippet is showing compilation error? Can you suggest the
corrections?
abstract class A
{
abstract int add(int a, int b);
}
class B extends A
{
}
Class B must implement inherited abstract method A.add() or else it must be
declared as abstract. 5
Abstract Class
6.Can we write explicit constructors in an abstract class?
Yes. abstract classes can have any number of constructors.

7. Can you identify the error in the below code?


abstract class AbstractClass
{
private abstract int abstractMethod();
}
abstract methods can’t be private.

6
Abstract Class
8.What will be the output of the following program?
abstract class A{ class C extends B{
abstract void firstMethod(); @Override
void secondMethod() void thirdMethod()
{System.out.println("SECOND"); {System.out.println("THIRD");}
firstMethod(); }
}} public class MainClass
abstract class B extends A{ {
@Override public static void main(String[] args)
void firstMethod(){ { FIRST
System.out.println("FIRST"); C c = new C(); THIRD
thirdMethod();} c.firstMethod(); SECOND
abstract void thirdMethod(); c.secondMethod(); FIRST
} c.thirdMethod(); THIRD
}} THIRD
7
Interface
9. A java interface can contain ————.
a) public static Final Variables only
b) public Abstract methods
c) Abstract methods(unimplemented) and
implemented methods both
d) public static Final Variables and abstract methods
both

8
Interface
10) Which is the correct way to inherit and implement
the interface?
Consider and example, Interface is IAnimal and a
class is Cat that wants to implement interface.
a) class Cat implements IAnimal{}
b) class Cat extends IAnimal{}
c) class Cat import IAnimal{}
d) None is correct
9
Interface
11) which of the following is true about methods in
an interface in java?
a) An interface can contain only abstract method.
b) We can define a method in an interface
c) Private and protected access modifiers can also
be used to declare methods in interface
d) None
10
Interface
12) What is output of the below java code?
interface X
{
int i = 5;
}
class Y implements X
{
void f()
{ i = 10;
System.out.println("i="+i);
} a) 0
} b) 5
public class Main {
c) 10
public static void main(String[] args) {
Y obj = new Y(); d) Compiler error
obj.f();
}
}
11
Interface
13) For every interface written in a java file, .class file will be generated after
compilation? True or False?

True. For every interface written in a java file, .class file will be generated after
compilation

14) Can interfaces have constructors?

No. Interfaces can’t have constructors.

12
Interface
interface A class C extends B implements A
{ {
void myMethod(); }
} class MainClass
class B {
{ public static void main(String[]
public void myMethod() args)
{ {
System.out.println("My A a = new C();
Method"); a.myMethod();
} }
} }
My Method 13
Interface
16) Why the below code is showing compile time error?
interface A
{
void myMethod();
}
class B
{
public void myMethod()
{
System.out.println("My Method");
}
}
interface methods must be implemented as public. Because, interface methods
are public by default and you should not reduce the visibility of any methods
while overriding. 14
Interface
17) Is the following code written correctly?
class A
{
//Class A
}
interface B extends A
{
//Interface B extending Class A
}

No. An interface can extend another interface not the class.

15
Interface
18) What should be given in the dotted lines?
class A
{
interface AA
{ void display();}
}
Class B implements ………….
{

}
A.AA

16
Interface
19)How do you print the value of field ‘i’ of interface ‘OneTwoThree’ in the below
example and what will be the it’s value?
interface One
{
int i = 222; System.out.println(One.OneTwo.OneTwoThree.i)
interface OneTwo 888.
{
int i = One.i+One.i;
interface OneTwoThree
{
int i = OneTwo.i + OneTwo.i;
}
}
}
17
Interface class Four extends Three implements One, Two
20) What will be the output of the following
program? {
interface One public String methodONE()
{ {
String s = "FINAL"; String s = super.s + One.s;
String methodONE(); return s;
}
NOTFINALFINAL
}
interface Two } FINAL
{ public class MainClass
String methodONE(); {
} public static void main(String[] args)
abstract class Three {
{ Four four = new Four();
String s = "NOT FINAL"; System.out.println(four.methodONE());
public abstract String methodONE(); One one = four;
} System.out.println(one.s);
}
} 18
Interface
21) Is the below program written correctly? If yes, public void methodY()
what will be the output?
interface X
{
{ System.out.println(3);
void methodX(); }
interface Y }
{ public class MainClass
void methodY(); { 3
} public static void main(String[] args) 2
} {
class Z implements X, X.Y
1
Z z = new Z();
{ z.methodX();
3
{ z.methodY(); 2
methodX(); X x = z; 3
System.out.println(1);
}
x.methodX(); 3
} 2
public void methodX()
}
{
methodY();
System.out.println(2); 19
}
MCQs
on
OVERLOADING
&
OVERRIDING
1
1. What is the process of defining two or more
methods within same class that have same name
but different parameters declaration?
a) method overloading
b) method overriding
c) method hiding
d) none of the mentioned

2
1. What is the process of defining two or more
methods within same class that have same name
but different parameters declaration?

a) method overloading
b) method overriding
c) method hiding
d) none of the mentioned

Explanation: Two or more methods can have same name as long


as their parameters declaration is different, the methods are said to
be overloaded and process is called method overloading. Method
overloading is a way by which Java implements polymorphism.
3
2. Which of these can be overloaded?
a) Methods

b) Constructors

c) All of the mentioned

d) None of the mentioned

4
2. Which of these can be overloaded?
a) Methods

b) Constructors

c) All of the mentioned


d) None of the mentioned

5
3. Which of these is correct about passing an argument
by call-by-value process?
a) Copy of argument is made into the formal parameter of the subroutine
b) Reference to original argument is passed to formal parameter of the
subroutine
c) Copy of argument is made into the formal parameter of the subroutine and
changes made on parameters of subroutine have effect on original argument
d) Reference to original argument is passed to formal parameter of the
subroutine and changes made on parameters of subroutine have effect on
original argument

6
3. Which of these is correct about passing an argument
by call-by-value process?
a) Copy of argument is made into the formal parameter of the
subroutine (explanation in next slide)
b) Reference to original argument is passed to formal parameter of the
subroutine
c) Copy of argument is made into the formal parameter of the subroutine and
changes made on parameters of subroutine have effect on original argument
d) Reference to original argument is passed to formal parameter of the
subroutine and changes made on parameters of subroutine have effect on
original argument
7
Explanation: When we pass an argument by call-by-value
a copy of argument is made into the formal parameter of
the subroutine and changes made on parameters of
subroutine have no effect on original argument, they remain
the same

8
4. What is the process of defining a method in
terms of itself, that is a method that calls itself?
a) Polymorphism
b) Abstraction
c) Encapsulation
d) Recursion

9
4. What is the process of defining a method in
terms of itself, that is a method that calls itself?
a) Polymorphism
b) Abstraction
c) Encapsulation

d) Recursion

10
5. What is the output of the following code?
class Sample
{ public void m1 (int i, float f)
{ System.out.println(" int float method"); }
public void m1(float f, int i);
{ System.out.println("float int method"); }
public static void main(String[]args)
{ Sample s=new Sample();
s.m1(20,25); }
}
a) int float method
b) float int method
c) compile time error
d) run time error
11
5. What is the output of the following code?
class Sample
{ public void m1 (int i, float f)
{ System.out.println(" int float method"); }
public void m1(float f, int i);
{ System.out.println("float int method"); }
public static void main(String[]args)
{ Sample s=new Sample();
s.m1(20,25); }
}
Explanation: While resolving overloaded
a) int float method
method, compiler automatically promotes if
b) float int method exact match is not found. But in this case, which
c) compile time error one to promote is an ambiguity.
d) run time error
12
6. What is the output of this program?
class overload
{ int x;
void add(int a) a) 5
{ x = a + 1; }
void add(int a, int b) b) 6
{ x = a + 2; } } // end of class c) 7
class Overload_methods
d) 8
{ public static void main(String args[])
{ overload obj = new overload();
int a = 0;
obj.add(6);
System.out.println(obj.x); } } // end of main class
13
6. What is the output of this program?
class overload
{ int x;
void add(int a) a) 5
{ x = a + 1; }
void add(int a, int b) b) 6
{ x = a + 2; } } // end of class
class Overload_methods
c) 7
{ public static void main(String args[]) d) 8
{ overload obj = new overload();
int a = 0;
obj.add(6);
System.out.println(obj.x); } } // end of main class
14
7. What is the output of this program?
class overload
{ int x;
void add(int a) a) 5
{ x = a + 1; }
void add(int a, int b) b) 6
{ x = a + 2; } } // end of class c) 7
class Overload_methods
d) 8
{ public static void main(String args[])
{ overload obj = new overload();
int a = 0;
obj.add(6, 7);
System.out.println(obj.x); } } // end of main class
15
7. What is the output of this program?
class overload
{ int x;
void add(int a) a) 5
{ x = a + 1; }
void add(int a, int b) b) 6
{ x = a + 2; } } // end of class c) 7
class Overload_methods
{ public static void main(String args[]) d) 8
{ overload obj = new overload();
int a = 0;
obj.add(6, 7);
System.out.println(obj.x); } } // end of main class
16
8. What is the output of this program?
class overload
{ int x; double y;
void add(double c, double d) { y = c + d; }
void add(int a, int b) { x = a + b; } a) 6 6
overload() { this.x=0; this.y=0;}
b) 6.4 6.4
}
class Overload_methods c) 6.4 6
{ public static void main(String args[])
d) 4 6.4
{ overload obj = new overload();
int a = 2; double b=3.2;
obj.add(a, a);
obj.add(b, b);
System.out.println(obj.x+” “+obj.y); }
} 17
8. What is the output of this program?
class overload
{ int x; double y;
void add(double c, double d) { y = c + d; }
void add(int a, int b) { x = a + b; } a) 6 6
overload() { this.x=0; this.y=0;}
b) 6.4 6.4
}
class Overload_methods c) 6.4 6
{ public static void main(String args[])
{ overload obj = new overload(); d) 4 6.4
int a = 2; double b=3.2;
obj.add(a, a);
obj.add(b, b);
System.out.println(obj.x+” “+obj.y); }
} 18
9. What is the output of this program?
class test
{ int a;
int b;
void math(int i , int j) { i *= 2; j /= 2; } } a) 10 20
class Output b) 20 10
{ public static void main(String args[])
c) 20 40
{ test obj = new test();
int a = 10; d) 40 20
int b = 20;
obj.math(a , b);
System.out.println(a + " " + b); } }
19
9. What is the output of this program?
class test
{ int a;
int b;
void math(int i , int j) { i *= 2; j /= 2; } }
class Output a) 10 20
{ public static void main(String args[])
{ test obj = new test(); b) 20 10
int a = 10; c) 20 40
int b = 20;
obj.math(a , b); d) 40 20
System.out.println(a + " " + b); } }

Explanation: Variables a & b are passed by value, copy of their values are made on
formal parameters of function math() that is i & j. Therefore changes done on i & j are
not reflected back on original arguments. a & b remain 10 & 20 respectively. 20
10. What is the output of this program?
class test
{ int a;
int b;
test(int i, int j) { a=i ; b=j; } a) 10 20
void math(test t) { t.a *= 2; t.b /= 2; } } b) 20 10
class Output
c) 20 40
{ public static void main(String args[])
{ test obj = new test(10, 20); d) 40 20
obj.math(obj);
System.out.println(obj.a + " " + obj.b); } }

21
10. What is the output of this program?
class test
{ int a;
int b;
test(int i, int j) { a=i ; b=j; } a) 10 20
void math(test t) { t.a *= 2; t.b /= 2; } }
class Output b) 20 10
{ public static void main(String args[])
{ test obj = new test(10, 20); c) 20 40
obj.math(obj);
System.out.println(obj.a + " " + obj.b);} } d) 40 20
Explanation: Class objects are always passed by reference, so,changes done
are reflected back on original arguments. obj.math(obj) sends object obj as
parameter whose variables a & b are multiplied and divided by 2 respectively
by math() function of class test. a & b becomes 20 & 10 respectively. 22
11. Which of this keyword can be used in a
subclass to call the constructor of superclass?
a) super
b) this
c) extent
d) extends

23
11. Which of this keyword can be used in a
subclass to call the constructor of superclass?
a) super
b) this
c) extent
d) extends

24
12. What is the process of defining a method in a
subclass having same name & type signature as a
method in its superclass?
a) Method overloading
b) Method overriding
c) Method hiding
d) None of the mentioned
25
12. What is the process of defining a method in a
subclass having same name & type signature as a
method in its superclass?
a) Method overloading

b) Method overriding
c) Method hiding
d) None of the mentioned
26
13. Which of these keywords can be used to prevent
Method overriding?
a) static
b) constant
c) protected
d) final

27
13. Which of these keywords can be used to prevent
Method overriding?
a) static
b) constant
c) protected
d) final
Explanation: To disallow a method from being overridden, specify
final as a modifier at the start of its declaration. Methods declared as
final cannot be overridden. 28
14. Which of these is correct way of calling a constructor
having no parameters, of superclass A by subclass B?
a) super(void);
b) superclass.();
c) super.A();
d) super();

29
14. Which of these is correct way of calling a constructor
having no parameters, of superclass A by subclass B?
a) super(void);
b) superclass.();
c) super.A();
d) super();

30
15. At line number 2 below, choose 3 valid data-type
attributes/qualifiers among “final, static, native, public,
private, abstract, protected”
public interface Status
{
/* insert qualifier here */ int MY_VALUE = 10;
}
a) final, native, private
b) final, static, protected
c) final, private, abstract
d) final, static, public

31
15. At line number 2 below, choose 3 valid data-type
attributes/qualifiers among “final, static, native, public,
private, abstract, protected”
public interface Status
{
/* insert qualifier here */ int MY_VALUE = 10;
}
a) final, native, private
b) final, static, protected
c) final, private, abstract
d) final, static, public
Explanation: Every interface variable is implicitly public static and final.
32
16. Which of these is supported by method overriding in Java?

a) Abstraction

b) Encapsulation

c) Polymorphism

d) None of the mentioned

33
16. Which of these is supported by method overriding in Java?

a) Abstraction

b) Encapsulation

c) Polymorphism

d) None of the mentioned

34
17. What is the output of this program?
class test
{
public static void main(String[] args)
{ int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}};
int [][]y = x;
System.out.println(y[2][1]); }
}
a) 2
b) 3
c) 7
d) Compilation Error

35
17. What is the output of this program?
class test
{
public static void main(String[] args)
{ int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}};
int [][]y = x;
System.out.println(y[2][1]); }
}
a) 2
b) 3
c) 7
d) Compilation Error

Explanation: Both x and y are pointing to the same array. 36


18. What is the output of this program?
final class A
{ int i; }
class B extends A
{ int j; a) 2 2
System.out.println(j + " " + i); } b) 3 3
class inheritance
c) Runtime Error
{
public static void main(String args[]) d) Compilation Error
{ B obj = new B();
obj.display(); }
}
37
18. What is the output of this program?
final class A
{ int i; }
class B extends A
{ int j; a) 2 2
System.out.println(j + " " + i); }
class inheritance b) 3 3
{
public static void main(String args[]) c) Runtime Error
{ B obj = new B();
obj.display(); } d) Compilation Error
}

Explanation: class A has been declared final hence it cannot be inherited


by any other class. Hence class B does not have member i, giving compilation
error. 38
19. What is the output of this program?
class Abc
{ public static void main(String[] args)
{ String[] elements = { “abc", “ABC", “aBc" };
String first = (elements.length > 0) ? elements[0]: null;
}
}
a) Compilation error
b) An exception is thrown at run time
c) The variable first is set to null
d) The variable first is set to elements[0]

39
19. What is the output of this program?
class Abc
{ public static void main(String[] args)
{ String[] elements = { “abc", “ABC", “aBc" };
String first = (elements.length > 0) ? elements[0]: null;
}
}
a) Compilation error
b) An exception is thrown at run time
c) The variable first is set to null
d) The variable first is set to elements[0]
Explanation: The value at the 0th position will be assigned to the
variable first. 40
20. What is the output of this program?
class A
{ int i;
public void display() { System.out.println(i); } }
class B extends A
a) 1
{ int j;
public void display() { System.out.println(j); } } b) 2
class Dynamic_dispatch
c) 3
{ public static void main(String args[])
{ B ch= new B(); ch.i = 1; ch.j = 2; d) 4
A p; p = ch; p.display(); }
}

41
20. What is the output of this program?
class A
{ int i;
public void display() { System.out.println(i); } }
class B extends A
a) 1
{ int j;
public void display() { System.out.println(j); } } b) 2
class Dynamic_dispatch
{ public static void main(String args[]) c) 3
{ B ch= new B(); ch.i = 1; ch.j = 2; d) 4
A p; p = ch; p.display(); }
}
Explanation: p is reference of type A, the program assigns a reference of
object ch to p and uses that reference to call function display() of class B
42
Thank You

43
MCQs
On

JAVA COLLECTIONS FRAMEWORK


1
1. Which of these packages contain all the collection
classes?
a) java.lang
b) java.util
c) java.net
d) java.awt

2
1. Which of these packages contain all the collection
classes?
a) java.lang

b) java.util
c) java.net
d) java.awt

3
2. Which of these classes is not part of Java’s
collection framework?
a) Maps
b) Array
c) Stack
d) Queue

4
2. Which of these classes is not part of Java’s
collection framework?
a) Maps
b) Array
c) Stack
d) Queue
Explanation: Maps is not a part of collection framework

5
3. Which of this interface is not a part of Java’s
collection framework?
a) List
b) Set
c) SortedMap
d) SortedList

6
3. Which of this interface is not a part of Java’s
collection framework?
a) List
b) Set
c) SortedMap

d) SortedList
Explanation: SortedList is not a part of collection framework

7
4. Which of these methods deletes all the elements
from invoking collection?
a) clear()
b) reset()
c) delete()
d) refresh()

8
4. Which of these methods deletes all the elements
from invoking collection?
a) clear()
b) reset()
c) delete()
d) refresh()
Explanation: clear() method removes all the elements from invoking
collection
9
5. What is Collection in Java?
a) A group of objects
b) A group of classes
c) A group of interfaces
d) None of the mentioned

10
5. What is Collection in Java?
a) A group of objects
b) A group of classes
c) A group of interfaces
d) None of the mentioned

Explanation: A collection is a group of objects, it is similar to String


Template Library (STL) of C++ programming language

11
6. What is the output of this program?
import java.util.*;
class Array
{ public static void main(String args[])
{ int array[] = new int [5]; a) 12885
for (int i = 5; i > 0; i--) b) 12845
array[5-i] = i;
Arrays.fill(array, 1, 4, 8); c) 58881
for (int i = 0; i < 5 ; i++)
System.out.print(array[i]); d) 54881
}
}

12
6. What is the output of this program?
import java.util.*;
class Array
{ public static void main(String args[])
{ int array[] = new int [5];
for (int i = 5; i > 0; i--) a) 12885
array[5-i] = i; b) 12845
Arrays.fill(array, 1, 4, 8);
for (int i = 0; i < 5 ; i++) c) 58881
System.out.print(array[i]);
} d) 54881
}
Explanation: array was containing 5,4,3,2,1 but when method
Arrays.fill(array, 1, 4, 8) is called it fills the index location starting with 1
to 4 by value 8 hence array becomes 5,8,8,8,1
13
7. What is the output of this program?
import java.util.*;
class Bitset
{
public static void main(String args[]) a) {0, 1, 3, 4}
{ b) {0, 1, 2, 4}
BitSet obj = new BitSet(5);
for (int i = 0; i < 5; ++i) c) {0, 1, 2, 3, 4}
obj.set(i);
obj.clear(2); d) {0, 0, 0, 3, 4}
System.out.print(obj);
}
}

14
7. What is the output of this program?
import java.util.*;
class Bitset
{
public static void main(String args[]) a) {0, 1, 3, 4}
{
BitSet obj = new BitSet(5); b) {0, 1, 2, 4}
for (int i = 0; i < 5; ++i)
obj.set(i); c) {0, 1, 2, 3, 4}
obj.clear(2); d) {0, 0, 0, 3, 4}
System.out.print(obj);
}
}

15
8. Which of these method is used to add an element
to the start of a LinkedList object?
a) add()
b) first()
c) AddFirst()
d) addFirst()

16
8. Which of these method is used to add an element
to the start of a LinkedList object?
a) add()
b) first()
c) AddFirst()

d) addFirst()

17
9. Which of these method of HashSet class is used to
add elements to its object?
a) add()
b) Add()
c) addFirst()
d) insert()

18
9. Which of these method of HashSet class is used to
add elements to its object?
a) add()
b) Add()
c) addFirst()
d) insert()

19
10. Which of these methods can be used to delete
the last element in a LinkedList object?
a) remove()
b) delete()
c) removeLast()
d) deleteLast()

20
10. Which of these methods can be used to delete
the last element in a LinkedList object?
a) remove()
b) delete()

c) removeLast()
d) deleteLast()
Explanation: removeLast() and removeFirst() methods are used to
remove elements in end and beginning of a linked list
21
11. Which of this method is used to change an element in a
LinkedList Object?
a) change()
b) set()
c) redo()
d) add()

22
11. Which of this method is used to change an element in a
LinkedList Object?
a) change()

b) set()
c) redo()
d) add()
Explanation: An element in a LinkedList object can be changed by first
using get() to obtain the index or location of that object and the passing
that location to method set() along with its new value 23
12. What is the output of this program?
import java.util.*;
class Linkedlist
{ public static void main(String args[])
{ LinkedList obj = new LinkedList(); a) [A, B, C].
obj.add("A"); b) [D, B, C].
obj.add("B");
obj.add("C"); c) [A, B, C, D].
obj.addFirst("D");
System.out.println(obj); d) [D, A, B, C].
}
}

24
12. What is the output of this program?
import java.util.*;
class Linkedlist
{ public static void main(String args[])
{ LinkedList obj = new LinkedList(); a) [A, B, C].
obj.add("A"); b) [D, B, C].
obj.add("B");
obj.add("C"); c) [A, B, C, D].
obj.addFirst("D");
System.out.println(obj); d) [D, A, B, C].
}
}
Explanation: obj.addFirst(“D”) method is used to add ‘D’ to the start of
a LinkedList object obj
25
13. What is the output of this program?
import java.util.*;
class Linkedlist
{ a) [A, B].
public static void main(String args[]) b) [B, C].
{
LinkedList obj = new LinkedList(); c) [A, B, C, D].
obj.add("A");
obj.add("B"); d) [A, B, C].
obj.add("C");
obj.removeFirst();
System.out.println(obj);
}
}
26
13. What is the output of this program?
import java.util.*;
class Linkedlist
{ a) [A, B].
public static void main(String args[])
{ b) [B, C].
LinkedList obj = new LinkedList();
obj.add("A"); c) [A, B, C, D].
obj.add("B"); d) [A, B, C].
obj.add("C");
obj.removeFirst();
System.out.println(obj);
}
}
27
14. What is the output of this program?
import java.util.*;
class Output
{ a) ABC 3
public static void main(String args[]) b) [A, B, C] 3
{
HashSet obj = new HashSet(); c) ABC 2
obj.add("A");
obj.add("B"); d) [A, B, C] 2
obj.add("C");
System.out.println(obj + " " + obj.size());
}
}

28
14. What is the output of this program?
import java.util.*;
class Output
{
public static void main(String args[]) a) ABC 3
{
HashSet obj = new HashSet(); b) [A, B, C] 3
obj.add("A");
obj.add("B"); c) ABC 2
obj.add("C"); d) [A, B, C] 2
System.out.println(obj + " " + obj.size());
}
}
Explanation: HashSet obj creates an hash object which implements Set
interface, obj.size() gives the number of elements stored in the object
obj which in this case is 3 29
15. What is the output of this program?
import java.util.*;
class Output
{ public static void main(String args[])
{ TreeSet t = new TreeSet(); a) [1, 3, 5, 8, 9].
t.add("3");
t.add("9"); b) [3, 4, 1, 8, 9].
t.add("1"); c) [9, 8, 4, 3, 1].
t.add("4");
d) [1, 3, 4, 8, 9].
t.add("8");
System.out.println(t);
}
}
30
15. What is the output of this program?
import java.util.*;
class Output
{ public static void main(String args[])
{ TreeSet t = new TreeSet();
a) [1, 3, 5, 8, 9].
t.add("3");
t.add("9"); b) [3, 4, 1, 8, 9].
t.add("1");
c) [9, 8, 4, 3, 1].
t.add("4");
t.add("8");
System.out.println(t);
d) [1, 3, 4, 8, 9].
}
}
Explanation: TreeSet class uses set to store the values added by
function add in ascending order using tree for storage 31
16. Which of these object stores association between
keys and values?
a) Hash table
b) Map
c) Array
d) String

32
16. Which of these object stores association between
keys and values?
a) Hash table

b) Map
c) Array
d) String

33
17. Which of these method is used to remove all
keys/values pair from the invoking map?
a) delete()
b) remove()
c) clear()
d) removeAll()

34
17. Which of these method is used to remove all
keys/values pair from the invoking map?
a) delete()

b) remove()
c) clear()
d) removeAll()

35
18. Which of these method Map class is used to
obtain an element in the map having specified key?
a) search()
b) get()
c) set()
d) look()

36
18. Which of these method Map class is used to
obtain an element in the map having specified key?
a) search()

b) get()
c) set()
d) look()

37
19. Which of these methods can be used to obtain set
of all keys in a map?
a) getAll()
b) getKeys()
c) keyall()
d) keySet()

38
19. Which of these methods can be used to obtain set
of all keys in a map?
a) getAll()
b) getKeys()
c) keyall()

d) keySet()
Explanation: keySet() methods is used to get a set containing all the
keys used in a map. This method provides set view of the keys in the
invoking map
39
20. Which of these method is used add an element and
corresponding key to a map?
a) put()
b) set()
c) redo()
d) add()

40
20. Which of these method is used add an element and
corresponding key to a map?
a) put()
b) set()
c) redo()
d) add()
Explanation: Maps revolve around two basic operations – get() and
put(). to put a value into a map, use put(), specifying the key and the
value. To obtain a value, call get() , passing the key as an argument. The
value is returned 41
21. What is the output of this program?
import java.util.*;
class Maps
{
public static void main(String args[]) a) {A 1, B 1, C 1}
{ b) {A, B, C}
HashMap obj = new HashMap();
obj.put("A", new Integer(1)); c) {A-1, B-1, C-1}
obj.put("B", new Integer(2));
obj.put("C", new Integer(3)); d) {A=1, B=2, C=3}
System.out.println(obj);
}
}

42
21. What is the output of this program?
import java.util.*;
class Maps
{
public static void main(String args[]) a) {A 1, B 1, C 1}
{ b) {A, B, C}
HashMap obj = new HashMap();
obj.put("A", new Integer(1)); c) {A-1, B-1, C-1}
obj.put("B", new Integer(2));
obj.put("C", new Integer(3)); d) {A=1, B=2, C=3}
System.out.println(obj);
}
}

43
22. What is the output of this program?
import java.util.*;
class Maps
{
public static void main(String args[]) a) [A, B, C].
{
HashMap obj = new HashMap(); b) {A, B, C}
obj.put("A", new Integer(1));
obj.put("B", new Integer(2)); c) {1, 2, 3}
obj.put("C", new Integer(3));
System.out.println(obj.keySet()); d) [1, 2, 3].
}
}

44
22. What is the output of this program?
import java.util.*;
class Maps
{
public static void main(String args[])
{ a) [A, B, C].
HashMap obj = new HashMap();
obj.put("A", new Integer(1)); b) {A, B, C}
obj.put("B", new Integer(2));
obj.put("C", new Integer(3)); c) {1, 2, 3}
System.out.println(obj.keySet());
} d) [1, 2, 3].
}
Explanation: keySet() method returns a set containing all the keys used
in the invoking map. Here keys are characters A, B & C. 1, 2, 3 are the
values given to these keys 45
23. What is the output of this program?
import java.util.*;
class Maps
{
public static void main(String args[]) a) 1
{
HashMap obj = new HashMap(); b) 2
obj.put("A", new Integer(1));
c) 3
obj.put("B", new Integer(2));
obj.put("C", new Integer(3)); d) null
System.out.println(obj.get("B"));
}
}

46
23. What is the output of this program?
import java.util.*;
class Maps
{
public static void main(String args[]) a) 1
{
HashMap obj = new HashMap(); b) 2
obj.put("A", new Integer(1));
obj.put("B", new Integer(2)); c) 3
obj.put("C", new Integer(3));
System.out.println(obj.get("B")); d) null
}
}
Explanation: obj.get(“B”) method is used to obtain the value
associated with key “B”, which is 2
47
24. What is the output of this program?
import java.util.*;
class Maps
{ a) [A, B, C].
public static void main(String args[])
{ b) [1, 2, 3].
TreeMap obj = new TreeMap();
c) {A=1, B=2, C=3}
obj.put("A", new Integer(1));
obj.put("B", new Integer(2)); d) [A=1, B=2, C=3].
obj.put("C", new Integer(3));
System.out.println(obj.entrySet());
}
}

48
24. What is the output of this program?
import java.util.*;
class Maps
{
public static void main(String args[]) a) [A, B, C].
{
TreeMap obj = new TreeMap(); b) [1, 2, 3].
obj.put("A", new Integer(1));
c) {A=1, B=2, C=3}
obj.put("B", new Integer(2));
obj.put("C", new Integer(3));
System.out.println(obj.entrySet()); d) [A=1, B=2, C=3].
}
}
Explanation: obj.entrySet() method is used to obtain a set that contains
the entries in the map. This method provides set view of the invoking map
49
25. Which of these class object can be used to form a dynamic
array?
a) ArrayList
b) Map
c) Vector
d) ArrayList & Vector

50
25. Which of these class object can be used to form a dynamic
array?
a) ArrayList
b) Map
c) Vector
d) ArrayList & Vector
Explanation: Vectors are dynamic arrays, it contains many legacy methods
that are not part of collection framework, and hence these methods are not
present in ArrayList. But both are used to form dynamic arrays
51
26. Which of these are legacy classes?
a) Stack
b) Hashtable
c) Vector
d) All of the mentioned

52
26. Which of these are legacy classes?
a) Stack
b) Hashtable
c) Vector
d) All of the mentioned
Explanation: Stack, Hashtable, Vector, Properties and Dictionary are
legacy classes

53
27. Which of these is the interface of legacy?
a) Map
b) Enumeration
c) HashMap
d) Hashtable

54
27. Which of these is the interface of legacy?
a) Map

b) Enumeration
c) HashMap
d) Hashtable

55
28. What is the name of a data member of class Vector which is
used to store a number of elements in the vector?
a) length
b) elements
c) elementCount
d) capacity

56
28. What is the name of a data member of class Vector which is
used to store a number of elements in the vector?
a) length
b) elements
c) elementCount
d) capacity

57
29. Which of these methods is used to add elements in vector
at specific location?
a) add()
b) set()
c) AddElement()
d) addElement()

58
29. Which of these methods is used to add elements in vector
at specific location?
a) add()
b) set()
c) AddElement()

d) addElement()
Explanation: addElement() is used to add data in the vector, to obtain
the data we use elementAt() and to first and last element we use
firstElement() and lastElement() respectively 59
30. What is the output of this program?
import java.util.*;
class vector
{ a) 0
public static void main(String args[])
{ b) 3
Vector obj = new Vector(4,2); c) 2
obj.addElement(new Integer(3));
obj.addElement(new Integer(2)); d) 5
obj.addElement(new Integer(5));
System.out.println(obj.elementAt(1));
}
}

60
30. What is the output of this program?
import java.util.*;
class vector
{
public static void main(String args[]) a) 0
{
Vector obj = new Vector(4,2); b) 3
obj.addElement(new Integer(3));
obj.addElement(new Integer(2)); c) 2
obj.addElement(new Integer(5)); d) 5
System.out.println(obj.elementAt(1));
}
}
Explanation: obj.elementAt(1) returns the value stored at index 1, which
is 2
61
31. What is the output of this program?
import java.util.*;
class vector
{ a) 2
public static void main(String args[])
{ b) 3
Vector obj = new Vector(4,2); c) 4
obj.addElement(new Integer(3));
obj.addElement(new Integer(2)); d) 6
obj.addElement(new Integer(5));
System.out.println(obj.capacity());
}
}

62
31. What is the output of this program?
import java.util.*;
class vector
{ a) 2
public static void main(String args[])
{ b) 3
Vector obj = new Vector(4,2);
obj.addElement(new Integer(3)); c) 4
obj.addElement(new Integer(2)); d) 6
obj.addElement(new Integer(5));
System.out.println(obj.capacity());
}
}

63
32. What is the output of this program?
import java.util.*;
class vector
{
public static void main(String args[]) a) [3, 2, 6].
{ b) [3, 2, 8].
Vector obj = new Vector(4,2);
c) [3, 2, 6, 8].
obj.addElement(new Integer(3));
obj.addElement(new Integer(2)); d) [3, 2, 8, 6].
obj.addElement(new Integer(6));
obj.insertElementAt(new Integer(8), 2);
System.out.println(obj);
}
}
64
32. What is the output of this program?
import java.util.*;
class vector
{
public static void main(String args[]) a) [3, 2, 6].
{ b) [3, 2, 8].
Vector obj = new Vector(4,2);
c) [3, 2, 6, 8].
obj.addElement(new Integer(3));
obj.addElement(new Integer(2)); d) [3, 2, 8, 6].
obj.addElement(new Integer(6));
obj.insertElementAt(new Integer(8), 2);
System.out.println(obj);
}
}
65
33. What is the output of this program?
import java.util.*;
class vector
{
public static void main(String args[]) a) 0
{
Vector obj = new Vector(4,2); b) 1
obj.addElement(new Integer(3)); c) true
obj.addElement(new Integer(2));
obj.addElement(new Integer(5)); d) false
obj.removeAll(obj);
System.out.println(obj.isEmpty());
}

66
33. What is the output of this program?
import java.util.*;
class vector
{ public static void main(String args[])
{ a) 0
Vector obj = new Vector(4,2);
obj.addElement(new Integer(3)); b) 1
obj.addElement(new Integer(2));
obj.addElement(new Integer(5)); c) true
obj.removeAll(obj); d) false
System.out.println(obj.isEmpty());
}
}
Explanation: firstly elements 3, 2, 5 are entered in the vector obj, but
when obj.removeAll(obj); is executed all the elements are deleted and
vector is empty, hence obj.isEmpty() returns true 67
34. What is the output of this program?
import java.util.*;
class stack
{ a) [3, 5].
public static void main(String args[])
{ b) [3, 2].
Stack obj = new Stack(); c) [3, 2, 5].
obj.push(new Integer(3));
obj.push(new Integer(2)); d) [3, 5, 2].
obj.pop();
obj.push(new Integer(5));
System.out.println(obj);
}
}
68
34. What is the output of this program?
import java.util.*;
class stack
{ public static void main(String args[])
{ Stack obj = new Stack(); a) [3, 5].
obj.push(new Integer(3));
obj.push(new Integer(2)); b) [3, 2].
obj.pop();
obj.push(new Integer(5)); c) [3, 2, 5].
System.out.println(obj); } } d) [3, 5, 2].
Explanation: push() and pop() are standard functions of the class stack,
push() inserts in the stack and pop removes from the stack. 3 & 2 are
inserted using push() the pop() is used which removes 2 from the stack
then again push is used to insert 5 hence stack contains elements 3 & 5
69
35. Which of these class object uses the key to store value?
a) Dictionary
b) Map
c) Hashtable
d) All of the mentioned

70
35. Which of these class object uses the key to store value?
a) Dictionary
b) Map
c) Hashtable

d) All of the mentioned

Explanation: Dictionary, Map & Hashtable all implement Map interface


hence all of them uses keys to store value in the object

71
36. Which of these method is used to insert value and its key?
a) put()
b) set()
c) insertElement()
d) addElement()

72
36. Which of these method is used to insert value and its key?
a) put()
b) set()
c) insertElement()
d) addElement()

73
37. Which of these is a class which uses String as a key to store
the value in object?
a) Array
b) ArrayList
c) Dictionary
d) Properties

74
37. Which of these is a class which uses String as a key to store
the value in object?
a) Array
b) ArrayList
c) Dictionary

d) Properties

75
38. Which of these methods is used to retrieve the elements in
properties object at specific location?
a) get()
b) Elementat()
c) ElementAt()
d) getProperty()

76
38. Which of these methods is used to retrieve the elements in
properties object at specific location?
a) get()
b) Elementat()
c) ElementAt()

d) getProperty()

77
39. What is the output of this program?
import java.util.*;
class hashtable
{ a) 0
public static void main(String args[])
{ b) 1
Hashtable obj = new Hashtable(); c) true
obj.put("A", new Integer(3));
obj.put("B", new Integer(2)); d) false
obj.put("C", new Integer(8));
System.out.print(obj.contains(new Integer(5)));
}
}

78
39. What is the output of this program?
import java.util.*;
class hashtable
{ public static void main(String args[])
{ Hashtable obj = new Hashtable(); a) 0
obj.put("A", new Integer(3));
obj.put("B", new Integer(2)); b) 1
obj.put("C", new Integer(8)); c) true
System.out.print(obj.contains(new Integer(5)));
} d) false
}

Explanation: Hashtable object obj contains values 3, 2, 8 when


obj.contains(new Integer(5)) is executed it searches for 5 in the hashtable
since it is not present false is returned
79
40. What is the output of this program?
import java.util.*;
class hashtable
{ a) 0
public static void main(String args[])
{ b) 1
Hashtable obj = new Hashtable(); c) 2
obj.put("A", new Integer(3));
obj.put("B", new Integer(2)); d) 3
obj.put("C", new Integer(8));
obj.clear();
System.out.print(obj.size());
}
}
80
40. What is the output of this program?
import java.util.*;
class hashtable
{ a) 0
public static void main(String args[])
{ b) 1
Hashtable obj = new Hashtable();
obj.put("A", new Integer(3)); c) 2
obj.put("B", new Integer(2)); d) 3
obj.put("C", new Integer(8));
obj.clear();
System.out.print(obj.size());
}
}
81
41. What is the output of this program?
import java.util.*;
class hashtable
{ a) {C=8, B=2}
public static void main(String args[])
{ b) [C=8, B=2].
Hashtable obj = new Hashtable();
obj.put("A", new Integer(3)); c) {A=3, C=8, B=2}
obj.put("B", new Integer(2));
obj.put("C", new Integer(8)); d) [A=3, C=8, B=2].
obj.remove(new String("A"));
System.out.print(obj);
}
}
82
41. What is the output of this program?
import java.util.*;
class hashtable
{ a) {C=8, B=2}
public static void main(String args[])
{ b) [C=8, B=2].
Hashtable obj = new Hashtable();
obj.put("A", new Integer(3)); c) {A=3, C=8, B=2}
obj.put("B", new Integer(2));
obj.put("C", new Integer(8)); d) [A=3, C=8, B=2].
obj.remove(new String("A"));
System.out.print(obj);
}
}
83
42. What is the output of this program?
import java.util.*;
class hashtable
{ a) {C=8, B=2}
public static void main(String args[])
{ b) [C=8, B=2].
Hashtable obj = new Hashtable();
obj.put("A", new Integer(3)); c) {A=3, C=8, B=2}
obj.put("B", new Integer(2));
obj.put("C", new Integer(8)); d) [A=3, C=8, B=2]
System.out.print(obj.toString());
}
}

84
42. What is the output of this program?
import java.util.*;
class hashtable
{
public static void main(String args[]) a) {C=8, B=2}
{
Hashtable obj = new Hashtable(); b) [C=8, B=2].
obj.put("A", new Integer(3));
obj.put("B", new Integer(2)); c) {A=3, C=8, B=2}
obj.put("C", new Integer(8));
System.out.print(obj.toString()); d) [A=3, C=8, B=2]
}
}
Explanation: obj.toString returns String equivalent of the hashtable, which
can also be obtained by simply writing System.out.print(obj); as print
system automatically converts the obj tostring equivalent 85
43. What is the output of this program?
import java.util.*;
class properties
{ a) {AB, BC, CD}
public static void main(String args[])
{ b) [AB, BC, CD].
Properties obj = new Properties();
obj.put("AB", new Integer(3)); c) [3, 2, 8].
obj.put("BC", new Integer(2));
obj.put("CD", new Integer(8)); d) {3, 2, 8}
System.out.print(obj.keySet());
}
}

86
43. What is the output of this program?
import java.util.*;
class properties
{
public static void main(String args[]) a) {AB, BC, CD}
{
Properties obj = new Properties();
obj.put("AB", new Integer(3)); b) [AB, BC, CD].
obj.put("BC", new Integer(2));
obj.put("CD", new Integer(8)); c) [3, 2, 8].
System.out.print(obj.keySet());
}
d) {3, 2, 8}
}
Explanation: obj.keySet() returns a set containing all the keys used in
properties object, here obj contains keys AB, BC, CD therefore obj.keySet()
returns [AB, BC, CD] 87
44. Which of these class can generate an array which can
increase and decrease in size automatically?
a) ArrayList()
b) DynamicList()
c) LinkedList()
d) MallocList()

88
44. Which of these class can generate an array which can
increase and decrease in size automatically?
a) ArrayList()
b) DynamicList()
c) LinkedList()
d) MallocList()

89
45. Which of these method can be used to increase the
capacity of ArrayList object manually?
a) Capacity()
b) increaseCapacity()
c) increasecapacity()
d) ensureCapacity()

90
45. Which of these method can be used to increase the
capacity of ArrayList object manually?
a) Capacity()
b) increaseCapacity()
c) increasecapacity()

d) ensureCapacity()
Explanation: When we add an element, the capacity of ArrayList object
increases automatically, but we can increase it manually to specified
length x by using function ensureCapacity(x); 91
46. Which of these method of ArrayList class is used to
obtain present size of an object?
a) size()
b) length()
c) index()
d) capacity()

92
46. Which of these method of ArrayList class is used to
obtain present size of an object?
a) size()
b) length()
c) index()
d) capacity()

93
47. Which of these methods can be used to obtain a
static array from an ArrayList object?
a) Array()
b) covertArray()
c) toArray()
d) covertoArray()

94
47. Which of these methods can be used to obtain a
static array from an ArrayList object?
a) Array()
b) covertArray()

c) toArray()
d) covertoArray()

95
48. Which of these method is used to reduce the
capacity of an ArrayList object?
a) trim()
b) trimSize()
c) trimTosize()
d) trimToSize()

96
48. Which of these method is used to reduce the
capacity of an ArrayList object?
a) trim()
b) trimSize()
c) trimTosize()

d) trimToSize()
Explanation: trimTosize() is used to reduce the size of the array that
underlines an ArrayList object
97
49. What is the output of this program?
import java.util.*;
class Arraylist
{
public static void main(String args[]) a) [A, B, C, D].
{
ArrayList obj = new ArrayList(); b) [A, D, B, C].
obj.add("A");
obj.add("B");
c) [A, D, C].
obj.add("C"); d) [A, B, C].
obj.add(1, "D");
System.out.println(obj);
}
}

98
49. What is the output of this program?
import java.util.*;
class Arraylist
{ public static void main(String args[])
{ ArrayList obj = new ArrayList(); a) [A, B, C, D].
obj.add("A");
obj.add("B"); b) [A, D, B, C].
obj.add("C");
obj.add(1, "D"); c) [A, D, C].
System.out.println(obj); } }
d) [A, B, C].
Explanation: obj is an object of class ArrayList hence it is an dynamic
array which can increase and decrease its size. obj.add(“X”) adds to the
array element X and obj.add(1,”X”) adds element x at index position 1 in
the list, Hence obj.add(1,”D”) stores D at index position 1 of obj and shifts
the previous value stored at that position by 1 99
50. What is the output of this program?
import java.util.*;
class Output
{ a) 0
public static void main(String args[])
{ b) 1
ArrayList obj = new ArrayList();
obj.add("A");
c) 2
obj.add(0, "B"); d) Any Garbage Value
System.out.println(obj.size());
}
}

100
50. What is the output of this program?
import java.util.*;
class Output
{ a) 0
public static void main(String args[])
{ b) 1
ArrayList obj = new ArrayList();
obj.add("A"); c) 2
obj.add(0, "B");
System.out.println(obj.size()); d) Any Garbage Value
}
}

101
51. What is the output of this program?
import java.util.*;
class Output a) 1
{
public static void main(String args[]) b) 2
{
ArrayList obj = new ArrayList(); c) 3
obj.add("A");
obj.ensureCapacity(3); d) 4
System.out.println(obj.size());
}
}

102
51. What is the output of this program?
import java.util.*;
class Output
{ public static void main(String args[])
{ ArrayList obj = new ArrayList(); a) 1
obj.add("A");
obj.ensureCapacity(3); b) 2
System.out.println(obj.size());
} c) 3
}
d) 4
Explanation: Although obj.ensureCapacity(3); has manually increased
the capacity of obj to 3 but the value is stored only at index 0, therefore
obj.size() returns the total number of elements stored in the obj i:e 1, it
has nothing to do with ensureCapacity()
103
52. What is the output of this program?
class Output
{ a) 1
public static void main(String args[])
{ b) 2
ArrayList obj = new ArrayList();
obj.add("A"); c) 3
obj.add("D");
obj.ensureCapacity(3); d) 4
obj.trimToSize();
System.out.println(obj.size());
}
}

104
52. What is the output of this program?
class Output
{
public static void main(String args[]) a) 1
{
ArrayList obj = new ArrayList();
obj.add("A"); b) 2
obj.add("D");
obj.ensureCapacity(3); c) 3
obj.trimToSize();
System.out.println(obj.size());
d) 4
}
}
Explanation: trimTosize() is used to reduce the size of the array that
underlines an ArrayList object
105
53. Map implements collection interface?

a) True

b) False

106
53. Map implements collection interface?

a) True

b) False

Explanation: Collection interface provides add, remove, search or

iterate while map has clear, get, put, remove, etc.

107
54. What is the premise of equality for IdentityHashMap?
a) Reference equality
b) Name equality
c) Hashcode equality
d) Length equality

108
54. What is the premise of equality for IdentityHashMap?
a) Reference equality
b) Name equality
c) Hashcode equality
d) Length equality

Explanation: IdentityHashMap is rarely used as it violates the basic


contract of implementing equals() and hashcode() method

109
55. What happens if we put a key object in a HashMap which
exists?
a) The new object replaces the older object
b) The new object is discarded
c) The old object is removed from the map
d) It throws an exception as the key already exists in the map

110
55. What happens if we put a key object in a HashMap which
exists?
a) The new object replaces the older object
b) The new object is discarded
c) The old object is removed from the map
d) It throws an exception as the key already exists in the map

Explanation: HashMap always contains unique keys. If same key is


inserted again, the new object replaces the previous object
111
56. While finding the correct location for saving key value pair,
how many times the key is hashed?
a) 1
b) 2
c) 3
d) unlimited till bucket is found

112
56. While finding the correct location for saving key value pair,
how many times the key is hashed?
a) 1
b) 2
c) 3
d) unlimited till bucket is found

Explanation: The key is hashed twice; first by hashCode() of Object class


and then by internal hashing method of HashMap class
113
57. Is hashmap an ordered collection.

a) True

b) False

114
57. Is hashmap an ordered collection

a) True

b) False

Explanation: Hashmap outputs in the order of hashcode of the keys. So

it is unordered but will always have same result for same set of keys

115
58. If two threads access the same hashmap at the same time,
what would happen?
a) ConcurrentModificationException
b) NullPointerException
c) ClassNotFoundException
d) RuntimeException

116
58. If two threads access the same hashmap at the same time,
what would happen?
a) ConcurrentModificationException
b) NullPointerException
c) ClassNotFoundException
d) RuntimeException

Explanation: The code will throw ConcurrentModificationException if


two threads access the same hashmap at the same time
117
59. How to externally synchronize hashmap?

a) HashMap.synchronize(HashMap a);

b) HashMap a = new HashMap(); a.synchronize();

c) Collections.synchronizedMap(new HashMap<String, String>());

d) Collections.synchronize(new HashMap<String, String>());

118
59. How to externally synchronize hashmap?
a) HashMap.synchronize(HashMap a);
b) HashMap a = new HashMap(); a.synchronize();

c) Collections.synchronizedMap(new HashMap<String, String>());


d) Collections.synchronize(new HashMap<String, String>());

Explanation: Collections.synchronizedMap() synchronizes entire map.


ConcurrentHashMap provides thread safety without synchronizing entire
map
119
60. What is the output of below snippet?
public class Demo
{ public static void main(String[] args)
{ Map<Integer, Object> sampleMap = new TreeMap<Integer, Object>();
sampleMap.put(1, null);
sampleMap.put(5, null);
sampleMap.put(3, null);
sampleMap.put(2, null); a) {1=null, 2=null, 3=null, 4=null, 5=null}
sampleMap.put(4, null);
b) {5=null}
System.out.println(sampleMap);
} c) Exception is thrown
} d) {1=null, 5=null, 3=null, 2=null, 4=null}

120
60. What is the output of below snippet?
public class Demo
{ public static void main(String[] args)
{ Map<Integer, Object> sampleMap = new TreeMap<Integer, Object>();
sampleMap.put(1, null);
sampleMap.put(5, null);
sampleMap.put(3, null); a) {1=null, 2=null, 3=null, 4=null, 5=null}
sampleMap.put(2, null); b) {5=null}
sampleMap.put(4, null);
System.out.println(sampleMap); c) Exception is thrown
} d) {1=null, 5=null, 3=null, 2=null, 4=null}
}
Explanation: HashMap needs unique keys. TreeMap sorts the keys while
storing objects
121
61. If large number of items are stored in hash bucket, what
happens to the internal structure?
a) The bucket will switch from LinkedList to BalancedTree
b) The bucket will increase its size by a factor of load size defined
c) The LinkedList will be replaced by another hashmap
d) Any further addition throws Overflow exception

122
61. If large number of items are stored in hash bucket, what
happens to the internal structure?
a) The bucket will switch from LinkedList to BalancedTree
b) The bucket will increase its size by a factor of load size defined
c) The LinkedList will be replaced by another hashmap
d) Any further addition throws Overflow exception

Explanation: BalancedTree will improve performance from O(n) to O(log n) by


reducing hash collisions
123
62. How can we remove an object from ArrayList?

a) remove() method

b) using Iterator

c) remove() method and using Iterator

d) delete() method

124
62. How can we remove an object from ArrayList?
a) remove() method
b) using Iterator

c) remove() method and using Iterator


d) delete() method

Explanation: There are 2 ways to remove an object from ArrayList. We can use
overloaded method remove(int index) or remove(Object obj). We can also use
an Iterator to remove the object
125
63. How to remove duplicates from List?

a) HashSet<String> listToSet = new HashSet<String>(duplicateList);

b) HashSet<String> listToSet = duplicateList.toSet();

c) HashSet<String> listToSet = Collections.convertToSet(duplicateList);

d) HashSet<String> listToSet = duplicateList.getSet();

126
63. How to remove duplicates from List?

a) HashSet<String> listToSet = new HashSet<String>(duplicateList);

b) HashSet<String> listToSet = duplicateList.toSet();

c) HashSet<String> listToSet = Collections.convertToSet(duplicateList);

d) HashSet<String> listToSet = duplicateList.getSet();

Explanation: Duplicate elements are allowed in List. Set contains unique

objects 127
64. How to sort elements of ArrayList?

a) Collection.sort(listObj);

b) Collections.sort(listObj);

c) listObj.sort();

d) Sorter.sortAsc(listObj);

128
64. How to sort elements of ArrayList?

a) Collection.sort(listObj);

b) Collections.sort(listObj);

c) listObj.sort();

d) Sorter.sortAsc(listObj);

Explanation: Collections provides a method to sort the list. The order of

sorting can be defined using Comparator 129


65. When two threads access the same ArrayList object what is the
outcome of the program?
a) Both are able to access the object
b) ConcurrentModificationException is thrown
c) One thread is able to access the object and second thread gets Null Pointer
exception
d) One thread is able to access the object and second thread will wait till
control is passed to the second one

130
65. When two threads access the same ArrayList object what is the
outcome of the program?
a) Both are able to access the object
b) ConcurrentModificationException is thrown
c) One thread is able to access the object and second thread gets Null Pointer
exception
d) One thread is able to access the object and second thread will wait till
control is passed to the second one
Explanation: ArrayList is not synchronized. Vector is the synchronized data
structure
131
66. How is Arrays.asList() different than the standard way of
initialising List?
a) Both are same
b) Arrays.asList() throws compilation error
c) Arrays.asList() returns a fixed length list and doesn’t allow to add or remove
elements
d) We cannot access the list returned using Arrays.asList()

132
66. How is Arrays.asList() different than the standard way of
initialising List?
a) Both are same
b) Arrays.asList() throws compilation error
c) Arrays.asList() returns a fixed length list and doesn’t allow to add
or remove elements
d) We cannot access the list returned using Arrays.asList()
Explanation: List returned by Arrays.asList() is a fixed length list which
doesn’t allow us to add or remove element from it.add() and remove() method
will throw UnSupportedOperationException if used 133
67. What is the difference between length() and size() of ArrayList?
a) length() and size() return the same value
b) length() is not defined in ArrayList
c) size() is not defined in ArrayList
d) length() returns the capacity of ArrayList and size() returns the actual
number of elements stored in the list

134
67. What is the difference between length() and size() of ArrayList?
a) length() and size() return the same value
b) length() is not defined in ArrayList
c) size() is not defined in ArrayList

d) length() returns the capacity of ArrayList and size() returns the


actual number of elements stored in the list
Explanation: length() returns the capacity of ArrayList and size() returns the
actual number of elements stored in the list which is always less than or equal
to capacity 135
68. Which class provides thread safe implementation of List?

a) ArrayList

b) CopyOnWriteArrayList

c) HashList

d) List

136
68. Which class provides thread safe implementation of List?
a) ArrayList
b) CopyOnWriteArrayList
c) HashList
d) List

Explanation: CopyOnWriteArrayList is a concurrent collection class. Its very


efficient if ArrayList is mostly used for reading purpose because it allows
multiple threads to read data without locking, which was not possible with
synchronized ArrayList
137
69. Which of the below is not an implementation of List interface?

a) RoleUnresolvedList

b) Stack

c) AttibuteList

d) SessionList

138
69. Which of the below is not an implementation of List interface?
a) RoleUnresolvedList
b) Stack
c) AttibuteList

d) SessionList

Explanation: SessionList is not an implementation of List interface. The


others are concrete classes of List

139
70. What is the worst case complexity of accessing an element in

ArrayList?

a) O(n)

b) O(1)

c) O(nlogn)

d) O(2)

140
70. What is the worst case complexity of accessing an element in
ArrayList?
a) O(n)
b) O(1)
c) O(nlogn)
d) O(2)

Explanation: ArrayList has O(1) complexity for accessing an element in


ArrayList. O(n) is the complexity for accessing an element from LinkedList

141
71. When an array is passed to a method, will the content of the

array undergo changes with the actions carried within the function?

a) True

b) False

142
71. When an array is passed to a method, will the content of the

array undergo changes with the actions carried within the function?

a) True

b) False

Explanation: If we make a copy of array before any changes to the array the

content will not change. Else the content of the array will undergo changes

143
72. What is the default clone of HashSet?

a) Deep clone

b) Shallow clone

c) Plain clone

d) Hollow clone

144
72. What is the default clone of HashSet?
a) Deep clone

b) Shallow clone
c) Plain clone

d) Hollow clone

Explanation: Default clone() method uses shallow copy. The internal


elements are not cloned. A shallow copy only copies the reference object

145
73. Do we have get(Object o) method in HashSet.

a) True

b) False

146
73. Do we have get(Object o) method in HashSet.

a) True

b) False

Explanation: get(Object o) method is useful when we want to compare

objects based on the comparison of values. HashSet does not provide any way

to compare objects. It just guarantees unique objects stored in the collection

147
74. What does Collections.emptySet() return?

a) Immutable Set

b) Mutable Set

c) The type of Set depends on the parameter passed to the emptySet() method

d) Null object

148
74. What does Collections.emptySet() return?
a) Immutable Set
b) Mutable Set
c) The type of Set depends on the parameter passed to the emptySet() method
d) Null object

Explanation: Immutable Set is useful in multithreaded environment. One


does not need to declare generic type collection. It is inferred by the context of
method call
149
75. What are the initial capacity and load factor of HashSet?

a) 10, 1.0

b) 32, 0.75

c) 16, 0.75

d) 32, 1.0

150
75. What are the initial capacity and load factor of HashSet?

a) 10, 1.0

b) 32, 0.75

c) 16, 0.75

d) 32, 1.0

Explanation: We should not set the initial capacity too high and load factor

too low if iteration performance is needed 151


76. What is the relation between hashset and hashmap?

a) HashSet internally implements HashMap

b) HashMap internally implements HashSet

c) HashMap is the interface; HashSet is the concrete class

d) HashSet is the interface; HashMap is the concrete class

152
76. What is the relation between hashset and hashmap?

a) HashSet internally implements HashMap


b) HashMap internally implements HashSet

c) HashMap is the interface; HashSet is the concrete class

d) HashSet is the interface; HashMap is the concrete class

Explanation: HashSet is implemented to provide uniqueness feature which is


not provided by HashMap. This also reduces code duplication and provides the

memory efficient behavior of HashMap 153


77. What is the output of below code snippet?
public class Test
{
public static void main(String[] args) a) Test - 10
{ Test - 10
Set s = new HashSet(); b) Test – 10
s.add(new Long(10)); c) Runtime Exception
s.add(new Integer(10)); d) Compilation Failure
for(Object object : s)
System.out.println("test - "+object);
}
}

154
77. What is the output of below code snippet?
public class Test
{
public static void main(String[] args) a) Test - 10
{ Test - 10
Set s = new HashSet(); b) Test – 10
s.add(new Long(10)); c) Runtime Exception
s.add(new Integer(10)); d) Compilation Failure
for(Object object : s)
System.out.println("test - "+object);
}
}

Explanation: Integer and Long are two different data types and different
objects. So they will be treated as unique elements and not overridden
155
78. Set has contains(Object o) method.

a) True

b) False

156
78. Set has contains(Object o) method.

a) True

b) False

Explanation: Set has contains(Object o) method instead of get(Object o)

method as get is needed for comparing object and getting corresponding value

157
79. What is the difference between TreeSet and SortedSet?

a) TreeSet is more efficient than SortedSet

b) SortedSet is more efficient than TreeSet

c) TreeSet is an interface; SortedSet is a concrete class

d) SortedSet is an interface; TreeSet is a concrete class

158
79. What is the difference between TreeSet and SortedSet?

a) TreeSet is more efficient than SortedSet

b) SortedSet is more efficient than TreeSet

c) TreeSet is an interface; SortedSet is a concrete class

d) SortedSet is an interface; TreeSet is a concrete class

Explanation: SortedSet is an interface. It maintains an ordered set of

elements. TreeSet is an implementation of SortedSet 159


80. What happens if two threads simultaneously modify TreeSet?

a) ConcurrentModificationException is thrown

b) Both threads can perform action successfully

c) FailFastException is thrown

d) IteratorModificationException is thrown

160
80. What happens if two threads simultaneously modify TreeSet?

a) ConcurrentModificationException is thrown

b) Both threads can perform action successfully

c) FailFastException is thrown

d) IteratorModificationException is thrown

Explanation: TreeSet provides fail-fast iterator. Hence when concurrently

modifying TreeSet it throws ConcurrentModificationException


161
81. What is the unique feature of LinkedHashSet?

a) It is not a valid class

b) It maintains the insertion order and guarantees uniqueness

c) It provides a way to store key values with uniqueness

d) The elements in the collection are linked to each other

162
81. What is the unique feature of LinkedHashSet?
a) It is not a valid class

b) It maintains the insertion order and guarantees uniqueness


c) It provides a way to store key values with uniqueness

d) The elements in the collection are linked to each other

Explanation: Set is a collection of unique elements.HashSet has the behavior


of Set and stores key value pairs. The LinkedHashSet stores the key value pairs

in the order of insertion 163


82. Which of these return type of hasNext() method of an iterator?

a) Integer

b) Double

c) Boolean

d) Collections Object

164
82. Which of these return type of hasNext() method of an iterator?

a) Integer

b) Double

c) Boolean

d) Collections Object

165
83. Which of these methods is used to obtain an iterator to the
start of collection?
a) start()
b) begin()
c) iteratorSet()
d) iterator()

166
83. Which of these methods is used to obtain an iterator to the
start of collection?
a) start()
b) begin()
c) iteratorSet()

d) iterator()

Explanation: To obtain an iterator to the start of the start of the collection we


use iterator() method
167
84. Which of these methods can be used to move to next element

in a collection?

a) next()

b) move()

c) shuffle()

d) hasNext()

168
84. Which of these methods can be used to move to next element

in a collection?

a) next()

b) move()

c) shuffle()

d) hasNext()

169
85. Which of these iterators can be used only with List?

a) Setiterator

b) ListIterator

c) Literator

d) None of the mentioned

170
85. Which of these iterators can be used only with List?

a) Setiterator

b) ListIterator

c) Literator

d) None of the mentioned

171
86. Which of these is a method of ListIterator used to obtain index

of previous element?

a) previous()

b) previousIndex()

c) back()

d) goBack()

172
86. Which of these is a method of ListIterator used to obtain index
of previous element?
a) previous()
b) previousIndex()
c) back()
d) goBack()

Explanation: previousIndex() returns index of previous element. if there is no


previous element then -1 is returned

173
87. Which of these exceptions is thrown by remover() method?

a) IOException

b) SystemException

c) ObjectNotFoundExeception

d) IllegalStateException

174
87. Which of these exceptions is thrown by remover() method?

a) IOException

b) SystemException

c) ObjectNotFoundExeception

d) IllegalStateException

175
88. What is the output of this program?
import java.util.*;
class Collection_iterators
{ a) 0
public static void main(String args[])
{ b) 1
ListIterator a = list.listIterator(); c) -1
if(a.previousIndex()! = -1)
while(a.hasNext()) d) EMPTY
System.out.print(a.next() + " ");
else
System.out.print("EMPTY");
}
}
176
88. What is the output of this program?
import java.util.*;
class Collection_iterators
{
public static void main(String args[]) a) 0
{
ListIterator a = list.listIterator(); b) 1
if(a.previousIndex()! = -1) c) -1
while(a.hasNext())
System.out.print(a.next() + " "); d) EMPTY
else
System.out.print("EMPTY");
}
}

177
89. What is the output of this program?
import java.util.*;
class Collection_iterators
{ public static void main(String args[])
{ LinkedList list = new LinkedList(); a) 2 8 5 1
list.add(new Integer(2));
list.add(new Integer(8)); b) 1 5 8 2
list.add(new Integer(5)); c) 2
list.add(new Integer(1));
Iterator i = list.iterator(); d) 2 1 8 5
Collections.reverse(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
178
89. What is the output of this program?
import java.util.*;
class Collection_iterators
{ public static void main(String args[])
{ LinkedList list = new LinkedList(); a) 2 8 5 1
list.add(new Integer(2));
list.add(new Integer(8)); b) 1 5 8 2
list.add(new Integer(5));
list.add(new Integer(1)); c) 2
Iterator i = list.iterator(); d) 2 1 8 5
Collections.reverse(list);
while(i.hasNext())
System.out.print(i.next() + " "); } }
Explanation: Collections.reverse(list) reverses the given list, the list was 2->8-
>5->1 after reversing it became 1->5->8->2
179
90. What is the output of this program?
import java.util.*;
class Collection_iterators
{ public static void main(String args[])
{ LinkedList list = new LinkedList(); a) 2 8 5 1
list.add(new Integer(2));
list.add(new Integer(8)); b) 1 5 8 2
list.add(new Integer(5)); c) 1 2 5 8
list.add(new Integer(1));
Iterator i = list.iterator(); d) 2 1 8 5
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
} 180
90. What is the output of this program?
import java.util.*;
class Collection_iterators
{ public static void main(String args[])
{ LinkedList list = new LinkedList(); a) 2 8 5 1
list.add(new Integer(2));
b) 1 5 8 2
list.add(new Integer(8));
list.add(new Integer(5)); c) 1 2 5 8
list.add(new Integer(1));
Iterator i = list.iterator(); d) 2 1 8 5
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext()) System.out.print(i.next() + " "); } }
Explanation: Collections.sort(list) sorts the given list, the list was 2->8->5->1
after sorting it became 1->2->5->8
181
91. What is the output of this program?
import java.util.*;
class Collection_iterators
{ public static void main(String args[])
{ LinkedList list = new LinkedList(); a) 2 8 5
list.add(new Integer(2));
b) 2 1 8
list.add(new Integer(8));
list.add(new Integer(5)); c) 2 5 8
list.add(new Integer(1));
Iterator i = list.iterator(); d) 8 5 1
Collections.reverse(list);
Collections.shuffle(list);
i.next(); i.remove();
while(i.hasNext()) System.out.print(i.next() + " ");
}
} 182
91. What is the output of this program?
import java.util.*;
class Collection_iterators
{ public static void main(String args[])
{ LinkedList list = new LinkedList();
list.add(new Integer(2)); a) 2 8 5
list.add(new Integer(8));
list.add(new Integer(5)); b) 2 1 8
list.add(new Integer(1));
Iterator i = list.iterator(); c) 2 5 8
Collections.reverse(list);
Collections.shuffle(list); // output will be different on your system
i.next(); i.remove();
d) 8 5 1
while(i.hasNext()) System.out.print(i.next() + " "); } }
Explanation: i.next() returns the next element in the iteration. i.remove()
removes from the underlying collection the last element returned by this iterator
(optional operation). This method can be called only once per call to next(). The
behavior of an iterator is unspecified if the underlying collection is modified while
the iteration is in progress in any way other than by calling this method 183
92. Which of the below is not a subinterface of Queue?

a) BlockingQueue

b) BlockingEnque

c) TransferQueue

d) BlockingQueue

184
92. Which of the below is not a subinterface of Queue?

a) BlockingQueue

b) BlockingEnque

c) TransferQueue

d) BlockingQueue

Explanation: BlockingQueue, TransferQueue and BlockingQueue are

subinterfaces of Queue 185


93. What is the remaining capacity of BlockingQueue whose
intrinsic capacity is not defined?
a) Integer.MAX_VALUE
b) BigDecimal.MAX_VALUE
c) 99999999
d) Integer.INFINITY

186
93. What is the remaining capacity of BlockingQueue whose
intrinsic capacity is not defined?
a) Integer.MAX_VALUE
b) BigDecimal.MAX_VALUE
c) 99999999
d) Integer.INFINITY

Explanation: A BlockingQueue without any intrinsic capacity constraints


always reports a remaining capacity of Integer.MAX_VALUE
187
94. PriorityQueue is thread safe.

a) True

b) False

188
94. PriorityQueue is thread safe.

a) True

b) False

Explanation: PriorityQueue is not synchronized.

BlockingPriorityQueue is the thread safe implementation

189
95. What is difference between dequeue() and peek() function
of java?
a) dequeue() and peek() remove and return the next time in line
b) dequeue() and peek() return the next item in line
c) dequeue() removes and returns the next item in line while peek()
returns the next item in line
d) peek() removes and returns the next item in line while dequeue()
returns the next item in line
190
95. What is difference between dequeue() and peek() function
of java?
a) dequeue() and peek() remove and return the next time in line
b) dequeue() and peek() return the next item in line
c) dequeue() removes and returns the next item in line while
peek() returns the next item in line
d) peek() removes and returns the next item in line while dequeue()
returns the next item in line
Explanation: dequeue() removes the item next in line. peek() returns the
item without removing it from the queue
191
96. What is the difference between Queue and Stack?
a) Stack is LIFO; Queue is FIFO
b) Queue is LIFO; Stack is FIFO
c) Stack and Queue is FIFO
d) Stack and Queue is LIFO

192
96. What is the difference between Queue and Stack?
a) Stack is LIFO; Queue is FIFO
b) Queue is LIFO; Stack is FIFO
c) Stack and Queue is FIFO
d) Stack and Queue is LIFO

Explanation: Stack is Last in First out (LIFO) and Queue is First in First
out(FIFO)

193
97. What is the correct method used to insert and delete items
from the queue?
a) push and pop
b) enqueue and dequeue
c) enqueue and peek
d) add and remove

194
97. What is the correct method used to insert and delete items
from the queue?
a) push and pop

b) enqueue and dequeue


c) enqueue and peek
d) add and remove
Explanation: enqueue is pushing item into queue; dequeue is removing
item from queue; peek returns object without removing it from queue.
Stack uses push and pop methods. add and remove are used in the list 195
98. Which data structure is used in Breadth First Traversal of a
graph?
a) Stack
b) Queue
c) Array
d) Tree

196
98. Which data structure is used in Breadth First Traversal of a
graph?
a) Stack

b) Queue
c) Array
d) Tree
Explanation: In Breadth First Traversal of graph the nodes at the same
level are accessed in the order of retrieval (i.e FIFO)
197
99. Where does a new element be inserted in linked list
implementation of a queue?
a) Head of list
b) Tail of list
c) At the centre of list
d) All the old entries are pushed and then the new element is inserted

198
99. Where does a new element be inserted in linked list
implementation of a queue?
a) Head of list

b) Tail of list
c) At the centre of list
d) All the old entries are pushed and then the new element is inserted
Explanation: To maintain FIFO, newer elements are inserted to the tail
of the list
199
100. Which of these standard collection classes implements all
the standard functions on list data structure?
a) Array
b) LinkedList
c) HashSet
d) AbstractSet

200
100. Which of these standard collection classes implements all
the standard functions on list data structure?
a) Array
b) LinkedList
c) HashSet
d) AbstractSet

201
101. Which of this method is used to make all elements of an
equal to specified value?
a) add()
b) fill()
c) all()
d) set()

202
101. Which of this method is used to make all elements of an
equal to specified value?
a) add()

b) fill()
c) all()
d) set()
Explanation: fill() method assigns a value to all the elements in an array,
in other words, it fills the array with specified value
203
102. Which of these method of Array class is used sort an array
or its subset?
a) binarysort()
b) bubblesort()
c) sort()
d) insert()

204
102. Which of these method of Array class is used sort an array
or its subset?
a) binarysort()
b) bubblesort()
c) sort()
d) insert()

205
103. Which of these methods can be used to search an element
in a list?
a) find()
b) sort()
c) get()
d) binaryserach()

206
103. Which of these methods can be used to search an element
in a list?
a) find()
b) sort()
c) get()
d) binaryserach()
Explanation: binaryserach() method uses binary search to find a
specified value. This method must be applied to sorted arrays
207
104. What is the output of this program?
import java.util.*;
class Arraylist
{ a) 0
public static void main(String args[])
{ b) 1
ArrayList obj1 = new ArrayList();
ArrayList obj2 = new ArrayList(); c) true
obj1.add("A"); d) false
obj1.add("B");
obj2.add("A");
obj2.add(1, "B");
System.out.println(obj1.equals(obj2));
}
} 208
104. What is the output of this program?
import java.util.*;
class Arraylist
{
public static void main(String args[]) a) 0
{
ArrayList obj1 = new ArrayList(); b) 1
ArrayList obj2 = new ArrayList();
obj1.add("A");
obj1.add("B"); c) true
obj2.add("A");
obj2.add(1, "B"); d) false
System.out.println(obj1.equals(obj2));
} }
Explanation: obj1 and obj2 are an object of class ArrayList hence it is a dyn
amic array which can increase and decrease its size. obj.add(“X”) adds to the
array element X and obj.add(1,”X”) adds element x at index position 1 in the li
st, Both the objects obj1 and obj2 contain same elements i:e A & B thus obj1.
equals(obj2) method returns true 209
105. What is the output of this program?
import java.util.*;
class Array
{ a) 12345
public static void main(String args[])
{ b) 54321
int array[] = new int [5]; c) 1234
for (int i = 5; i > 0; i--)
array[5 - i] = i; d) 5432
Arrays.sort(array);
for (int i = 0; i < 5; ++i)
System.out.print(array[i]);;
}
}
210
105. What is the output of this program?
import java.util.*;
class Array
{
public static void main(String args[])
a) 12345
{ b) 54321
int array[] = new int [5];
for (int i = 5; i > 0; i--) c) 1234
array[5 - i] = i;
Arrays.sort(array); d) 5432
for (int i = 0; i < 5; ++i)
System.out.print(array[i]);;
}
}
Explanation: Arrays.sort(array) method sorts the array into 1,2,3,4,5
211
106. What is the output of this program?
import java.util.*;
class Array a) 2
{
public static void main(String args[]) b) 3
{
int array[] = new int [5]; c) 4
for (int i = 5; i > 0; i--)
array[5 - i] = i; d) 5
Arrays.sort(array);
System.out.print(Arrays.binarySearch(array, 4));
}
}
212
106. What is the output of this program?
import java.util.*;
class Array a) 2
{
public static void main(String args[]) b) 3
{
int array[] = new int [5]; c) 4
for (int i = 5; i > 0; i--)
array[5 - i] = i; d) 5
Arrays.sort(array);
System.out.print(Arrays.binarySearch(array, 4));
}
}
213
107. Which of these interface declares core method that all
collections will have?
a) set
b) EventListner
c) Comparator
d) Collection

214
107. Which of these interface declares core method that all
collections will have?
a) set
b) EventListner
c) Comparator
d) Collection
Explanation: Collection interfaces defines core methods that all the
collections like set, map, arrays etc will have
215
108. Which of these interface handle sequences?

a) Set

b) List

c) Comparator

d) Collection

216
108. Which of these interface handle sequences?

a) Set

b) List

c) Comparator

d) Collection

217
109. Which of this interface must contain a unique element?

a) Set

b) List

c) Array

d) Collection

218
109. Which of this interface must contain a unique element?
a) Set
b) List
c) Array
d) Collection

Explanation: Set interface extends collection interface to handle sets,


which must contain unique elements

219
110. Which of these is a Basic interface that all other interface
inherits?
a) Set
b) Array
c) List
d) Collection

220
110. Which of these is a Basic interface that all other interface
inherits?
a) Set
b) Array
c) List
d) Collection
Explanation: Collection interface is inherited by all other interfaces like
Set, Array, Map etc. It defines core methods that all the collections like
set, map, arrays etc will have 221
111. Which of these is static variable defined in
Collections?
a) EMPTY_SET
b) EMPTY_LIST
c) EMPTY_MAP
d) All of the mentioned

222
111. Which of these is static variable defined in
Collections?
a) EMPTY_SET
b) EMPTY_LIST
c) EMPTY_MAP

d) All of the mentioned

223
112. What is the output of this program?
import java.util.*;
class Array
{ a) 12345
public static void main(String args[])
{ b) 54321
int array[] = new int [5];
for (int i = 5; i > 0; i--) c) 1234
array[5 - i] = i; d) 5432
Arrays.sort(array);
for (int i = 0; i < 5; ++i)
System.out.print(array[i]);;
}
}
224
112. What is the output of this program?
import java.util.*;
class Array
{
public static void main(String args[]) a) 12345
{
b) 54321
int array[] = new int [5];
for (int i = 5; i > 0; i--) c) 1234
array[5 - i] = i;
Arrays.sort(array); d) 5432
for (int i = 0; i < 5; ++i)
System.out.print(array[i]);;
} }

Explanation: Arrays.sort(array) method sorts the array into 1,2,3,4,5


225
113. What is the output of this program?
import java.util.*;
class Collection_Algos
{ public static void main(String args[])
{ LinkedList list = new LinkedList(); a) 2 8 5 1
list.add(new Integer(2));
list.add(new Integer(8)); b) 1 5 8 2
list.add(new Integer(5)); c) 1 2 5 8
list.add(new Integer(1));
Iterator i = list.iterator(); d) 2 1 8 5
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext())
System.out.print(i.next() + " "); } }
226
113. What is the output of this program?
import java.util.*;
class Collection_Algos
{ public static void main(String args[])
{ LinkedList list = new LinkedList(); a) 2 8 5 1
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
b) 1 5 8 2
list.add(new Integer(1));
Iterator i = list.iterator(); c) 1 2 5 8
Collections.reverse(list);
Collections.sort(list); d) 2 1 8 5
while(i.hasNext())
System.out.print(i.next() + " "); } }
Explanation: Collections.sort(list) sorts the given list, the list was 2->8-
>5->1 after sorting it became 1->2->5->8
227
114. What is the output of this program?
import java.util.*;
class Collection_Algos
{ public static void main(String args[]) a) 2 8 5 1
{ LinkedList list = new LinkedList();
list.add(new Integer(2)); b) 1 5 8 2
list.add(new Integer(8));
list.add(new Integer(5)); c) 1 2 5 8
list.add(new Integer(1));
Iterator i = list.iterator(); d) Any random order
Collections.reverse(list);
Collections.shuffle(list);
while(i.hasNext())
System.out.print(i.next() + " "); } }
228
114. What is the output of this program?
import java.util.*;
class Collection_Algos
{ public static void main(String args[]) a) 2 8 5 1
{ LinkedList list = new LinkedList();
list.add(new Integer(2)); b) 1 5 8 2
list.add(new Integer(8));
list.add(new Integer(5)); c) 1 2 5 8
list.add(new Integer(1));
Iterator i = list.iterator(); d) Any random order
Collections.reverse(list);
Collections.shuffle(list); // output will be different on your system
while(i.hasNext())
System.out.print(i.next() + " "); } }
Explanation: shuffle – randomizes all the elements in a list. 229
115. Which of these is an incorrect form of using method max()
to obtain a maximum element?
a) max(Collection c)
b) max(Collection c, Comparator comp)
c) max(Comparator comp)
d) max(List c)

230
115. Which of these is an incorrect form of using method max()
to obtain a maximum element?
a) max(Collection c)
b) max(Collection c, Comparator comp)
c) max(Comparator comp)
d) max(List c)
Explanation: Its illegal to call max() only with comparator, we need to
give the collection to be searched into
231
116. Which of these methods can randomize all elements in a
list?
a) rand()
b) randomize()
c) shuffle()
d) ambiguous()

232
116. Which of these methods can randomize all elements in a
list?
a) rand()
b) randomize()

c) shuffle()
d) ambiguous()

Explanation: shuffle – randomizes all the elements in a list


233
117. Which of these methods can convert an object into a List?
a) SetList()
b) ConvertList()
c) singletonList()
d) CopyList()

234
117. Which of these methods can convert an object into a List?
a) SetList()
b) ConvertList()
c) singletonList()
d) CopyList()

Explanation: singletonList() returns the object as an immutable List. This


is an easy way to convert a single object into a list

235
118. Which of these is true about unmodifiableCollection()
method?
a) unmodifiableCollection() returns a collection that cannot be modified
b) unmodifiableCollection() method is available only for List and Set
c) unmodifiableCollection() is defined in Collection class
d) none of the mentioned

236
118. Which of these is true about unmodifiableCollection()
method?
a) unmodifiableCollection() returns a collection that cannot be modified
b) unmodifiableCollection() method is available only for List and Set
c) unmodifiableCollection() is defined in Collection class
d) none of the mentioned
Explanation: unmodifiableCollection() is available for all collections, Set,
Map, List etc.
237
Thank You

238
Java Revision- MCQ s
Java Fundamentals
1. Which three are valid declarations of a char?
1. char c1 = 064770;
2. char c2 = 'face'; a) 1, 2, 4
3. char c3 = 0xbeef; b) 1, 3, 6
c) 3, 5
4. char c4 = \u0022;
d) 5 only
5. char c5 = '\iface';
6. char c6 = '\uface';
Java Fundamentals
2. What is the output of the following program?
public class Test
{
public static void main(String[] args) a) 677
{ b) Compilation error due to line 1
byte var = 1; c) Compilation error due to line 2
var = (byte) var * 0; //line 1 d) Compilation error due to line 1 and line
byte data = (byte) (var * 0); //line 2 2
System.out.println(var);
}
}
Java Fundamentals
3. What is the output for the below code ?
public class Test{
int _$;
int $7;
int do; a) 790
b) 700
public static void main(String argv[]){
c) Compile error - $7 is not valid
Test test = new Test(); identifier.
test.$7=7; d) Compile error - do is not valid
identifier
test.do=9;
System.out.print(test.$7);
Sytem.out.print(test.do);
System.out.print(test._$);
} }
Java Fundamentals
4. What is the output for the below code ?
public class Test {
public static void main(String[] args){
byte b = 6;
b+=8; //Line1
System.out.println(b); a)14 21
b)14 13
b = b+7; // Line2
c)Compilation fails with an error at line 2
System.out.println(b);
d)Compilation fails with an error at line 1
}
}
Java Fundamentals
5. What is the output for the below code ?

public class Test {


public static void main(String[] args)
{ a) 22
int x =5; b) 50
x *= 3 + 7; c) 10
System.out.println(x); d) Compilation fails with an error at
line 4
}
}
Java Fundamentals
6. What is the output of this program?
class jump_statments else if (y == 8)
{ break;
public static void main(String args[]) else
{ System.out.print(y + " ");
int x = 2;int y = 0; }
for ( ; y < 10; ++y) } a) 1 3 5 7
{ } b) 2 4 6 8
if (y % x == 0) c) 1 3 5 7 9
continue; d) 1 2 3 4 5 6 7 8 9
Java Fundamentals
7. What is the output of this program?
int a = 5;int b = 10;
first:
{
second:
{
third:
{ a) 5 10
if (a == b >> 1)
b) 10 5
break second;
}
c) 5
System.out.println(a); d) 10
}
System.out.println(b);
}
Java Fundamentals
8.Which one will be faster?
a) for(int i = 0; i < 1000; i++) {} //Line1
b) for(int i = 1000; i > 0; i- -) {} //Line2

a) Line 1 will be faster


b) Line 2 will be faster
c) Both will give same performance
d) None of the above
Java Fundamentals
9.Identify the concept:
a) Line 1 is called unboxing
import java.io.*;
class Demo
Line 2 is called Autoboxing
{ public static void main (String[] args) b) Line 2 is called unboxing
{ Integer i = new Integer(10); Line 1 is called Autoboxing
int i1 = i; //Line1 a) Compiler Error
System.out.println("Value of i: " + i); b) None of the Above
System.out.println("Value of i1: " + i1);
Character gfg = 'a'; //Line 2
char ch = gfg;
System.out.println("Value of ch: " + ch);
System.out.println("Value of gfg: " + gfg);
}}
Java Fundamentals
10.Given:
1. class Voop {
2. public static void main(String[] args) {
3. doStuff(1); • Which, inserted independently at line 6, will
compile? (Choose all that apply.)
4. doStuff(1,2);
• A. static void doStuff(int... doArgs) { }
5. }
• B. static void doStuff(int[] doArgs) { }
6. // insert code here • C. static void doStuff(int doArgs...) { }
7. } • D. static void doStuff(int... doArgs, int y) { }
• E. static void doStuff(int x, int... doArgs) { }
Declarations and Access control
11.Predict the output??
public class Test
{ public static void main(String[] args) A. Two
{ String str = "two";
B. Compile time Error
switch(str)
{
C. Runtime Error
case "one": System.out.println("one");
break;
case "two": System.out.println("two");
break;
default:
System.out.println("no match");
}
}
Declarations and Access control
12.public class Tester {
static int p = test(); //line 1
A. 099
static public int test() {
B. Compilation error at line 1, p must be
System.out.print(p); //line 4 initialized by a value
return 99; C. Compilation error at line 4, using
} uninitialized variable p
public static void main(String[] args) D. Compilation error at line 11, p must
be called using its class by writing
{ Tester.p
System.out.print(p);//line 11
}
}
FlowControl
13. What will be the output of the following code?
class Test
{
public static void main(String args[])
{
int x = 7;
if(x == 2);
System.out.println(“NumberSeven”);
a. NumberSeven NotSeven
System.out.println(“NotSeven”); b. NumberSeven
} c. NotSeven
} d. Compilation Error
e. 7
Arrays
14.Predicit the output??
public static void main(String[] args) { A. An Exception will be
thrown
String entries[] = {"entry1","entry2"};
B. 0 will be printed as part
int count=0; of the output
while (entries [count++]!=null){ C. 2 will be printed as part
System.out.println(count); of the output
} D. 3 will be printed as part
System.out.println(count); of the output
}
Arrays
15. Predict the Output??
public class Tester {
static void test(int[] a) { A. 225
int[] b = new int[2];
B. 255
a = b;
C. 200
System.out.print(b.length);
System.out.print(a.length);
}
public static void main(String[] args) {
int[] a = new int[5];
test(a);
System.out.print(a.length);
}
}
Strings

16.Which of the following methods is used to compare two Strings in a


Java program? And if the Strings don’t match, then it returns a non-zero
value.
A.compareTo(String str)
B.equalsIgnoreCase(String str)
C.equals(String str)
D.None of these
Strings
17.What is the result of compiling and running the following code?
public class Tester {
public static void main(String[] args) {
String stmt = "JavaChamp is here to help you";
for (String token : stmt.split("//s")) {
System.out.print(token + " ");
} A. JavaChamp is here to help you
} B. JavaChamp i here to help you
} C. No output is produced
D. Compilation error
Strings
18.What is the result of compiling and running the following code?
public class Tester {
public static void main(String[] args) {
Scanner sc = new Scanner("javachamp 2009, true 239");
while (sc.hasNext()) {
if (sc.hasNextBoolean())
System.out.print("Boolean");
if (sc.hasNextInt())
System.out.print("Int"); A. IntBooleanInt
sc.next();
B. BooleanInt
}}}
C. IntInt
D. Compilation error
Strings
19.Select the common methods, which are defined for both type String
and type StringBuffer?
• Please choose all the answers that apply:
A. toString()
B. length()
C. append(String)
D. trim()
E. equals(Object)
Strings
20.Predict the output.
public static void main(String[] args) {
boolean stmt1 = "champ" == "champ";
boolean stmt2 = new String("champ") == "champ";
boolean stmt3 = new String("champ") == new String("champ");
System.out.println(stmt1 && stmt2 || stmt3);
}
Please choose only one answer:
A. true
B. false
Strings
21.Predict the output
public static void main(String[] args) {
String s1 = null;
String s2 = null;
A. AB; will be printed
if (s1 == s2)
B. A; will be printed
System.out.print("A"); C. NullPointerException thrown
if (s1.equals(s2)) D. B; will be printed
E. No output is produced
System.out.print("B");
}
OOP Concept
22.public class Profile {
private Profile(int w) { // line 1 A. Won't compile because of line (1) ;
System.out.println(w); constructor can't be private
} B. 10
public static Profile() { // line 5 50
System.out.println(10); C. 50
} D. Won't compile because of line (5);
constructor can't be static
public static void main(String args[]) {
Profile obj = new Profile(50);
}
}
OOP Concept
23. Given:
public abstract class Shape {
private int x; C. public class Circle extends Shape {
private int y; private int radius;
public abstract void draw(); public void draw();}
public void setAnchor(int x, int y) { D. public abstract class Circle implements Shap
this.x = x; private int radius;
this.y = y; public void draw();}
} }
E. public class Circle extends Shape {
Which two classes use the Shape class correctly?
private int radius;
(Choose two.)
public void draw() {/* code here */}
A. public class Circle implements Shape {
F. public abstract class Circle implements Shape
private int radius; }
private int radius;
B. public abstract class Circle extends Shape {
public void draw() { /* code here */ }
private int radius; }
OOP concept
24.Given: Which is most likely true? (Choose the
1. ClassA has a ClassD most likely.)
2. Methods in ClassA use public A. ClassD has low cohesion
methods in ClassB B. ClassA has weak encapsulation
3. Methods in ClassC use public C. ClassB has weak encapsulation
methods in ClassA D. ClassB has strong encapsulation
4. Methods in ClassA use public E. ClassC is tightly coupled to ClassA
variables in ClassB
OOP Concept
25.Given the following,
1. class X { void do1() { } }
2. class Y extends X { void do2() { } } Which, inserted at line 9, will
3. class Chrome { compile? (Choose all that apply.)
5. public static void main(String [] args) { A. x2.do2();
6. X x1 = new X(); B. (Y)x2.do2();
7. X x2 = new Y(); C. ((Y)x2).do2();
8. Y y1 = new Y(); D. None of the above statements
9. // insert code here will compile
10. }
11. }
OOP Concept
26.Which is true? (Choose all that apply.)
A. "X extends Y" is correct if and only if X is a class and Y is an
interface
B. "X extends Y" is correct if and only if X is an interface and Y is
a class
C. "X extends Y" is correct if X and Y are either both classes or
both interfaces
D. "X extends Y" is correct for all combinations of X and Y being
classes and/or interfaces
OOP Concept
27.Given:
1. class Dog {
2. public void bark() { System.out.print("woof "); }
3. }
4. class Hound extends Dog {
5. public void sniff() { System.out.print("sniff "); }
6. }
7. public class DogShow { What is the result? (Choose all that apply.)
8. public static void main(String[] args) A. howl howl sniff
9. { new DogShow().go(); } B. howl woof sniff
10. void go() { C. howl howl followed by an exception
11. new Hound().bark(); D. howl woof followed by an exception
12. ((Dog) new Hound()).bark(); E. Compilation fails with an error at line 12
13. ((Dog) new Hound()).sniff(); F. Compilation fails with an error at line 13
OOP Concept
28.Given:
public class Tenor extends Singer {
What is the result?
public static String sing() { return "fa"; }
A. fa fa
public static void main(String[] args) {
B. fa la
Tenor t = new Tenor();
C. la la
Singer s = new Tenor();
D. Compilation fails
System.out.println(t.sing() + " " + s.sing());
E. An exception is thrown at
} runtime
}
class Singer { public static String sing() { return "la"; } }
OOP Concept
29.public class A { public class Test{
int i = 10; public static void main(String
argv[]){
public void printValue() {
A a = new B();
System.out.println("Value-A");}
a.printValue();
}
System.out.println(a.i); } }
public class B extends A{
int i = 12; A.Value-B 11
B.Value-B 10
public void printValue() {
C.Value-A 10
System.out.print("Value-B");
D.Value-A 11
}}
OOP Concept
30.What is the result of compiling and public class Derived extends Base {
running the following code?
public int getNext(int i) { return i++; }
class Base
{
public static void main(String[] args)
public final int getNext(int i)
{
{
int result = new Derived().getNext(3);
return ++i;
System.out.print(result);
}
result = new Base().getNext(3);
} • 34 System.out.print(result);
• 44 }
• 43 }
• A compilation error

Вам также может понравиться