0% found this document useful (0 votes)
233 views

Java MCQ'S

The document contains a series of questions about Java concepts like data types, enums, dates, strings, classes, objects, memory management, inheritance, abstraction, polymorphism, and more. It does not provide any answers.
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
233 views

Java MCQ'S

The document contains a series of questions about Java concepts like data types, enums, dates, strings, classes, objects, memory management, inheritance, abstraction, polymorphism, and more. It does not provide any answers.
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 161

Questionnaire

 What is the numerical range of a char data type in Java?


Which of these coding types is used for data type characters in Java?
Which of these values can a boolean variable contain?
Which of these occupy first 0 to 127 in Unicode character set used for characters in Java?
Which one is a valid declaration of a boolean
What is the order of variables in Enum?
 Can we create an instance of Enum outside of Enum itself?
 What will be the output of the following Java code?
enum Season
{
If weWINTER, SPRING,
try to add SUMMER,to
Enum constants FALL
a TreeSet, what sorting order will it use?
};
System.out.println(Season.WINTER.ordinal());
What will be the output of the following Java code snippet?
class A
{
}
enum Enums extends A
{
ABC, BCD, CDE, DEF;
}

What will be the output of the following Java code snippet?


enum Levels
{
private TOP,
public MEDIUM,

protected BOTTOM;
}

Which method returns the elements of Enum class?


Which of the following is the advantage of BigDecimal over double?
Which of the below data type doesn’t support overloaded methods for +,-,* and /?
What will be the output of the following Java code snippet?
double a = 0.02;
double b = 0.03;
double c = b - a;
System.out.println(c);
BigDecimal _a = new BigDecimal("0.02");
BigDecimal _b = new BigDecimal("0.03");
BigDecimal _c = b.subtract(_a);
System.out.println(_c);

 How to format date from one form to another?


How to convert Date object to String?
How to convert a String to a Date object?

Is SimpleDateFormat thread safe?


How to identify if a timezone is eligible for DayLight Saving?

How is Date stored in database?


How to get difference between two dates?

What will be the output of the following Java program?


class evaluate
{
public static void main(String args[])
{
int a[] = {1,2,3,4,5};
Whatint will
d[] =be a;the output of the following Java program?
int sum = 0;
forarray_output
class (int j = 0; j < 3; ++j)
{ sum += (a[j] * d[j + 1]) + (a[j + 1] * d[j]);
System.out.println(sum);
public static void main(String args[])
{}
} int array_variable [] = new int[10];
Whatfor will
(int be
i = the
0; i <output of {the following Java program?
10; ++i)
class variable_scope
array_variable[i] = i/2;
{ array_variable[i]++;
public static void main(String args[]) + " ");
System.out.print(array_variable[i]
{ i++;
int
} x;
x = 5;
Which } {of these is an incorrect string literal?
} int y = 6;
System.out.print(x + " " + y);
What will } be the error in the following Java code?
byte b System.out.println(x
= 50; + " " + y);
b =} b * 50;
}
If an expression contains double, int, float, long, then the whole expression will be

What will be the output of the following Java code?


class char_increment
{
public static void main(String args[])
{
char c1 = 'D';
char c2 = 84;
c2++;
c1++;
What will be the output of the following Java code?
System.out.println(c1 + " " + c2);
class}conversion
}{
public static void main(String args[])
{
double a = 295.04;
int b = 300;
byte c = (byte) a;
byte d = (byte) b;
System.out.println(c + " " + d);
}
}
What will be the output of the following Java code?
class A
{
final public int calculate(int a, int b) { return 1; }
}
class B extends A
{
public int calculate(int a, int b) { return 2; }
}
public class output
{
public static void main(String args[])
{
What will be the= output
B object new B();of the following Java program, if we run as “java
main_arguments 1 2 3”? is " + b.calculate(0, 1));
System.out.print("b
class}main_arguments
{}
public static void main(String [] args)
{
String [][] argument = new String[2][2];
int x;
argument[0] = args;
x = argument[0].length;
Which for of these
(int y is anyincorrect
= 0; < x; y++) array declaration?
System.out.print(" " + argument[0][y]);
Which } of these is an incorrect Statement?
}

Which of the following is a superclass of every class in Java?

What will be the output of the following Java code?

class Output
{
public static void main(String args[])
What{ will be the output of the following Java code snippet?
double x = 3.14;
import intjava.util.*;
y = (int) Math.ceil(x);
class System.out.print(y);
Arraylists
{ }
} public static void main(String args[])
{
ArrayLists obj = new ArrayLists();
obj.add("A");
obj.add("B");
obj.add("C");
obj.add(1, "D");
System.out.println(obj);
}
What will be the output of the following Java code?
}
class newthread extends Thread
{
Thread t;
newthread()
{
t1
Which = new
one ofThread(this,"Thread_1");
the following is not an access modifier?
t2 = new Thread(this,"Thread_2");
t1.start();
t2.start();
}
public void run()
{
What is the stored in the object obj in following lines of Java code?
t2.setPriority(Thread.MAX_PRIORITY);
System.out.print(t1.equals(t2));
 Which of these keywords is used to make a class?
}
}
class multithreaded_programing
{
public static void main(String args[])
{
Which of the following is a valid declaration of an object of class Box?

Which of these operators is used to allocate memory for an object?

Which of these statement is incorrect?

Which of the following statements is correct?

What is the return type of a method that does not return any value?

What is the process of defining more than one method in a class differentiated by

Which of the following is a method having same name as that of it’s class?

Which method can be defined only once in a program?

Which of this statement is incorrect?

What is the return type of Constructors?

Which keyword is used by the method to refer to the object that invoked it?

Which of the following is a method having same name as that of its class?

 Which operator is used by Java run time implementations to free the memory of an object when it is no longer needed?

Which function is used to perform some action when the object is to be


destroyed?
Which of the following statements are incorrect?

What is true about private constructor?

 What would be the behaviour if this() and super() used in a method?

What is false about constructor?

What is true about Class.getInstance()?

What is true about constructor?

Abstract class cannot have a constructor.

What is true about protected constructor?

What is not the use of “this” keyword in Java?

What would be the behaviour if one parameterized constructor is explicitly defined

 What would be behaviour if the constructor has a return type?

Which of the following has the highest memory requirement?

Where is a new object allocated memory?

Which of the following is a garbage collection technique?

 What is -Xms and -Xmx while starting jvm?


Which exception is thrown when java is out of memory?

How to get prints of shared object memory maps or heap memory maps for a given

What happens to the thread when garbage collection kicks off?

 Which of the below is not a Java Profiler?

Which of the below is not a memory leak solution?

Garbage Collection can be controlled by a program?

What is the process of defining two or more methods within same class that have s

Which of these can be overloaded?

Which of these is correct about passing an argument by call-by-value process?

What is the process of defining a method in terms of itself, that is a method that calls

Which of these access specifiers must be used for main() method?

Which of these is used to access a member of class before object of that class is cre

Which of these is used as a default for a member of a class if no access specifier is us

What is the process by which we can control what parts of a program can access th

Which of the following statements are incorrect?

Which of these access specifier must be used for class so that it can be inherited by
Which one of the following is not an access modifier?

All the variables of class should be ideally declared as?

Which of the following modifier means a particular variable cannot be accessed wit

How can a protected modifier be accessed?

What happens if constructor of class A is made private?

All the variables of interface should be?

What is true of final class?

How many copies of static and class variables are created when 10 objects are create

Can a class be declared with a protected modifier.

Which is the modifier when there is none mentioned explicitly?

 Arrays in Java are implemented as?

Which of these keywords is used to prevent content of a variable from being modifi

Which of these cannot be declared static?

Which of the following statements are incorrect?


Which of the following statements are incorrect?

Which of these methods must be made static?

String in Java is a?
Which of these method of String class is used to obtain character at specified index?

Which of these keywords is used to refer to member of base class from a subclass?

Which of these method of String class can be used to test to strings for equality?

Which of the following statements are incorrect?

Which of these is the method which is executed first before execution of any other

What is the process of defining more than one method in a class differentiated by

Which of these can be used to differentiate two or more methods having the same
Which of these data type can be used for a method having a return statement in it?

Which of these statement is incorrect?

 What is Recursion in Java?

Which of these data types is used by operating system to manage the Recursion in J

Which of these will happen if recursive method does not have a base case?

Which of this keyword can be used in a subclass to call the constructor of superclass
What is the process of defining a method in a subclass having same name & type sig

Which of these keywords can be used to prevent Method overriding?


Which of these is correct way of calling a constructor having no parameters, of supe
At line number 2 in the following code,
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;
}
Which of these is supported by method overriding in Java?

What will be the output of the following Java program?


class Alligator
{
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]);
}
}

 Which of these class is superclass of every class in Java?


 Which of these method of Object class can clone an object?
Which of these method of Object class is used to obtain class of an object at run ti

Which of these keywords can be used to prevent inheritance of a class?

What will be the output of the following Java program?


abstract class A
{
int i;
abstract void display();
Which of these keywords cannot be used }for a class which has been declared final?
class B extends A
Which of these class relies upon its subclasses { for complete implementation of its
int j;
void display()
{
System.out.println(j);
}
}
class Abstract_demo
{
Which of these keywords are used
public to define
static an abstractargs[])
void main(String class?
Which of these is not abstract? {
B obj = new B();
obj.j=2;
obj.display();
If a class inheriting an abstract class does not } define all of its function then it will
}

Which mode allows us to run program interactively while watching source code and
Which of these class is superclass of String and StringBuffer class?

Which of these operators can be used to concatenate two or more String objects?
public class genericstack <E>
{
Stack <E> stk = new Stack <E>();
public void push(E obj)
{
What will be the output of the following Java code?
stk.push(obj);
import
} java.util.*;
publicE class
public pop()genericstack <E>
{ {
Which Stack <E>
Eofobj
this stk = new
= method of Stack
stk.pop(); <E>(); is used to obtain a length of String object?
class String
public
returnvoid push(E obj)
obj;
Which of these method of class String is used to extract a single character from a Str
} {
Which
} stk.push(obj);
of these constructors is used to create an empty String object?
} class Output
public
{ E pop()
Which of these is an incorrect statement?
{public static void main(String args[])
{ E obj = stk.pop();
return obj;
genericstack <String> gs = new genericstack<String>();
} gs.push("Hello");
} System.out.println(gs.pop());
class} Output
{}
public static void main(String args[])
{
genericstack <Integer> gs = new genericstack<Integer>();
gs.push(36);
System.out.println(gs.pop());
}
}

What are generic methods?

Which of the following allows us to call generic methods as a normal method?


When does Exceptions in Java arises in code sequence?

Which of these keywords is not a part of exception handling?


Which of these keywords must be used to monitor for exceptions?

 Which of these keywords must be used to handle the exception thrown by try block in some rational manner?

What will be the output of the following Java program?


class exception_handling
{
public static void main(String args[])
{
try
{
System.out.print("Hello" + " " + 1 / 0);
}
catch(ArithmeticException e)
{
System.out.print("World");
}
}
}

Which of these is a super class of all exceptional type classes?


Which of these class is related to all the exceptions that can be caught by using catc

Which of these class is related to all the exceptions that cannot be caught?

What exception thrown by parseInt() method?


What will be the output of the following Java code?
class exception_handling
{
public static void main(String args[])
{
try
{
System.out.print("Hello" + " " + 1 / 0);
}
finally
What will be the output of the following Java code?
{
class exception_handling
{ System.out.print("World");
} static void main(String args[])
public
}{
} try
{
int a = args.length;
int b = 10 / a;
System.out.print(a);
Which oftry these keywords is used to generate an exception explicitly?
{
Which of theseif (a class
== 1) is related to all the exceptions that are explicitly thrown?
a = a / a - a;
if (a == 2)
{
int []c = {1};
c[8] = 9;
Which of these} operator is used to generate an instance of an exception than can b
}
catch (ArrayIndexOutOfBoundException e)
{
System.out.println("TypeA");
}
catch (ArithmeticException e)
{
System.out.println("TypeB");
}
}
}
}
What will be the output of the following Java code?
class exception_handling
{
public static void main(String args[])
{
try
{
System.out.print("A");
throw new NullPointerException ("Hello");
}
catch(ArithmeticException e)
{
System.out.print("B");
}
}
}
What will be the output of the following Java code?
public class San
{
public static void main(String[] args)
{
try
{
return;
}
finally
{
System.out.println( "Finally" );
}
}
}

 Which of these clause will be executed even if no exceptions are found?

A single try block must be followed by which of these?

Which of these exceptions handles the divide by zero error?

Which of these exceptions will occur if we try to access the index of an array beyond
 What is the use of try & catch?

Which of these keywords are used for the block to be examined for exceptions?
Which of these keywords are used for the block to handle the exceptions generated
Which of these keywords are used for generating an exception manually?

Which of these statements is incorrect?


What will be the output of the following Java code?
class Output
{
public static void main(String args[])
{
try
{
int a = 0;
What willintbeb the
= 5;output of the following Java code?
int c = b / a;
System.out.print("Hello");
class Output
{ }
catch(Exception
public e)
static void main(String args[])
{{
trySystem.out.print("World");
{}
} int a = 0;
} int b = 5;
int c = a / b;
System.out.print("Hello");
} be the output of the following Java code?
What will
catch(Exception e)
class{ Output
{ System.out.print("World");
}
public static void main(String args[])
}{
} try
{
int a = 0;
What willintbeb the
= 5;output of the following Java code?
int c = b / a;
class Output
System.out.print("Hello");
{ }
public
} static void main(String args[])
} {
try
{
int a = 0;
int b = 5;
int c = a / b;
Which ofSystem.out.print("Hello");
these classes is used to define exceptions?
}
finally
{
Which ofSystem.out.print("World");
these methods return description of an exception?
Which}of these methods is used to print stack trace?
}
Which
} of these classes is super class of Exception class?
What will be the output of the following Java code?

class Myexception extends Exception


What
{ will be the output of the following Java code?
int detail;
class Myexception extends
Myexception(int a) Exception
What
{ { will be the output of the following Java code?
int detail;
classdetail = a;
exception_handling
} { Myexception(int
What will be
a)
the output of the following Java code?
public{ String toString()
public
detail =static
a; void main(String args[])
{{ Myexception
} return "detail"; extends Exception
class
{
public try
String toString()
}int detail;
{
{
} Myexception(int
return throw
"detail"; a)
new NullPointerException ("Hello");
class Output
}{ { System.out.print("A");
} detail} = a;
static void compute (int a) throws
} class catch(ArithmeticException
Output e) Myexception
public{ {String toString()
{ throw new Myexception(a);
{static
System.out.print("B");
void compute (int a) throws Myexception
} return
public { }static
"detail";
void main(String args[])
} throw} new Myexception(a);
{
}}
classtry
public Output
static void main(String args[])
{ { {
What will be the output of the following Java code?
class exception_handling
{
public static void main(String args[])
{
try
{
Which ofint thisa method
= args.length;
can be used to make the main thread to be executed last amon
int b = 10 / a;
System.out.print(a);
try
Which of{this method is used to find out that a thread is still running or not?
What is the ifdefault (a == 1)
value of priority variable MIN_PRIORITY AND MAX_PRIORITY?
a = a / a - a;
if (a == 2)
{
Which of theseintmethod c = {1};waits for the thread to terminate?
c[8] = 9;
}
}
catch (ArrayIndexOutOfBoundException e)
Which of{these method is used to explicitly set the priority of a thread?
System.out.println("TypeA");
}
catch (ArithmeticException e)
What is synchronization
{ in reference to a thread?
What will be the output of the following Java code?
System.out.println("TypeB");
}
class}newthread extends Thread
{ }
newthread()
}
{
super("My Thread");
start();
}
What
publicwill voidberun()
the output of the following Java code?
{
class newthread extends Thread
System.out.println(this);
}{
Thread
} t;
newthread()
class multithreaded_programing
{ { will be the output of the following Java code?
What
t =public
new Thread(this,"My Thread");
static void main(String args[])
t.start();
class { newthread extends Thread
}{ new newthread();
public
Thread } voidt; run()
} {
newthread()
What{ will try be the output of the following Java code?
t = new{ Thread(this,"New Thread");
t.start();t.join() extends Thread
class newthread
} { System.out.println(t.getName());
Thread}void
public run()
t1,t2;
{ catch(Exception e)
newthread()
{ {
System.out.println(t.isAlive());
} t1 = System.out.print("Exception");
new Thread(this,"Thread_1");
}t2 = }new Thread(this,"Thread_2");
} class
Which of these method is used to implement Runnable interface?
multithreaded_programing
t1.start();
{}t2.start();
Which of these method is used to begin the execution of a thread?
} class multithreaded_programing
public static void main(String args[])
{ { void run()
public
public
{ new static void main(String args[])
newthread();
{
}
t2.setPriority(Thread.MAX_PRIORITY);
new newthread();
}System.out.print(t1.equals(t2));
}}
}}
 Which
class of these statement is incorrect?
multithreaded_programing
{
public static void main(String args[])
{
new newthread();
}
}
What will be the output of the following Java code?
class newthread implements Runnable
{
Thread t;
newthread()
What{ will be the output of the following Java code?
t = new Thread(this,"My Thread");
class t.start();
newthread implements Runnable
}{
What
publicwill
Thread t; berun()
void the output of the following Java code?
newthread() {
class { newthread implements Runnable
System.out.println(t.getName());
} {t = new Thread(this,"My Thread");
Thread
What}t.start(); willt; be the output of the following Java code?
newthread()
} class multithreaded_programing
{ { void
class
public newthread
run() implements Runnable
{t ={public new Thread(this,"My Thread");
static void main(String args[])
What
Thread t.start();
{ will t; be the output of the following Java code?
System.out.println(t);
}newthread()
} new newthread();
}} {} newthread implements Runnable
class
class
{class
}t = new multithreaded_programing
Thread(this,"New Thread");
multithreaded_programing
{{t.start();
Thread t;
} public
newthread()public static void
void main(String
staticmethod main(String args[])
 Which
public { void of these
run() of Threadargs[])
class is used to find out the priority given to a thread?
Which new
t1{ = newnew
of newthread();
Thread(this,"Thread_1");
these method of Thread class is used to Suspend a thread for a period of
newthread();
t2}} = new Thread(this,"Thread_2");
t.setPriority(Thread.MAX_PRIORITY);
}}t1.start();
System.out.println(t);
} t2.start();
}}
public
Which void
classfunction run()of pre defined class Thread is used to check weather current thread b
multithreaded_programing
{ {
What will be the output of the following Java code?
t2.setPriority(Thread.MAX_PRIORITY);
public static void main(String args[])
System.out.print(t1.equals(t2));
class { multithreaded_programing
{ } new newthread();
} }public static void main(String args[])
What class
} { ismultithreaded_programing
the priority of the thread in output in the following Java program?
{ Thread t = Thread.currentThread();
class public static void main(String
Thread"); args[])
multithreaded_programing
t.setName("New
{ { System.out.println(t);
Whatpublic } isnew newthread();
thestatic
namevoid main(String
of the thread in args[])
output in the following Java program?
} }
{
}classThread t = Thread.currentThread();
multithreaded_programing
{ t.setName("New Thread");
Whatpublic isSystem.out.println(t.getName());
thestatic
namevoid main(String
of the thread in args[])
output in the following Java program?
}{
}classThread t = Thread.currentThread();
multithreaded_programing
{ System.out.println(t.getPriority());
What}public static void main(String
is multithreaded programming?args[])
} {
Thread t = Thread.currentThread();
System.out.println(t.isAlive());
}
Which } of these are types of multitasking?

Thread priority in Java is?

 What will happen if two thread of the same priority are called to be processed simultaneously?

Which of these statements is incorrect?


What will be the output of the following Java code?
class multithreaded_programing
What
{ is the priority of the thread in the following Java Program?
public static void main(String args[])
class
{ multithreaded_programing
What
{ isThread
the name of the thread in the following Java Program?
t = Thread.currentThread();
public static void main(String args[])
System.out.println(t);
class
{ multithreaded_programing
{ } Thread t = Thread.currentThread();
} public static void main(String args[])
System.out.println(t);
{}
} Thread t = Thread.currentThread();
System.out.println(t);
What requires less resources?
}
}

What does not prevent JVM from terminating?

What decides thread priority?

Deadlock is a situation when thread is waiting for other thread to release acquired o

What should not be done to avoid deadlock?

What is true about threading?

 Which of the following is a correct constructor for thread?

Which of the following stops execution of a thread?

 Which of the following will ensure the thread will be in running state?

Which of these keywords are used to implement synchronization?

Which of this method is used to avoid polling in Java?

Which of these method is used to tell the calling thread to give up a monitor and g
What will be the output of the following Java program?
class newthread extends Thread
{
What
Thread will
t; be the output of the following Java program?
String name;
class newthread threadname)
newthread(String extends Thread
{ {
Thread
namet;= threadname;
String name;
t = new Thread(this,name);
newthread(String
t.start(); threadname)
} {
name
public = threadname;
void run()
t ={ new Thread(this,name);
t.start();
}
}
public void run()
What will be the output of the following Java program?
class newthread extends Thread
{
Thread t;
String name;
What does AWT stands
newthread(String for?
threadname)
{
name
Which of=these
threadname;
is used to perform all input & output operations in Java?
t = new Thread(this,name);
t.start();
}
Which of these is a type of stream in Java?
public void run()
{
}
Which of these classes are used by Byte streams for input and output operation?
}
class multithreaded_programing
Which
{ of these classes are used by character streams for input and output operatio
Whatpublic
will be the output
static of the following
void main(String args[]) Java program if input given is
‘abcqfghqbcd’?
{
Whatnewthread
will be theobj1 = new
output newthread("one");
of the following Java program if input given is
class Input_Output
newthread
“abc’def/’egh”? obj2 = new newthread("two");
{ try
public
class static void main(String args[]) throws IOException
{Input_Output
{ { will System.out.print(obj1.t.equals(obj2.t));
What be the output of the following Java program?
char c; void main(String args[]) throws IOException
} static
public
{ BufferedReader
class catch(Exception
output obj
e) = new BufferedReader(new
InputStreamReader(System.in));
{ {char c;
do
System.out.print("Main
public obj =thread
static void main(String
BufferedReader interrupted");
args[])
new BufferedReader(new
{
Which }exception
{
InputStreamReader(System.in));
is thrown
c = (char) obj.read();by read() method?
} do StringBuffer c = new StringBuffer("Hello");
} System.out.print(c);
{System.out.println(c.length());
} } while(c != 'q');
c = (char) obj.read();
} }System.out.print(c);
Which
} of these is used to read a string from the input stream?
} while(c!='\'');
}
}
Which of these class is used to read characters and strings in Java from console?
What will be the output of the following Java program if input given is “Hello stop
World”?

class Input_Output
{
Whatpublic
will be the output
static of the following
void main(String args[]) Java program?
throws IOException
{
classstring
output str;
{ BufferedReader obj = new BufferedReader(new
public static void main(String args[])
InputStreamReader(System.in));
{ do
{StringBuffer c = new StringBuffer("Hello");
Which of StringBuffer
(char)c1
the=following
str =isnew
not StringBuffer(" World");
a class of java.util.regex?
obj.readLine();
c.append(c1);
System.out.print(str);
}System.out.println(c);
while(!str.equals("strong"));
}}
}} is the significance of Matcher class for regular expression in java?
What

Object of which class is used to compile regular expression?

what does public String replaceAll(string replace) do?

What is an event in delegation event model used by Java programming language?


 Which of these methods are used to register a keyboard event listener?
Event class is defined in which of these libraries?

Which of these methods can be used to determine the type of event?

Which of these class is super class of all the events?

Which of these events will be notified if scroll bar is manipulated?

 Which of these events will be generated if we close an applet’s window?


Which of these methods can be used to obtain the command name for invoking Act

Which of these methods can be used to know which key is pressed?


Which of these events is generated by scroll bar?

Which of these events is generated when the size of an event is changed?


Which of these methods can be used to obtain the reference to the container that

Which of these events is generated when the window is closed?

Which of these methods can be used to obtain the coordinates of a mouse?

Which of these is a mechanism for naming and visibility control of a class and its co

Which of this access specifies can be used for a class so that its members can be acc
Which of these access specifiers can be used for a class so that its members can be a

Which of the following is the correct way of importing an entire package ‘pkg’?
What will be the output of the following Java program?

package pkg;
What
classwill be the output of the following Java program?
display
{
package
intof pkg;
x; these
Which
class output can be used to fully abstract a class from its implementation?
void show()
{ {
public
if (x >static
1) void main(String args[])
{ System.out.print(x + " ");
} StringBuffer s1 = new StringBuffer("Hello");
} s1.setCharAt(1, x);
classSystem.out.println(s1);
packages
{ }
} public static void main(String args[])
Which of these access specifiers can be used for an interface?
{
Which display[]
of the following
arr=newisdisplay[3];
the correct way of implementing an interface salary by cl
for(int
What will i=0;i<3;i++)
be the output of the following Java program?
arr[i]=new display();
arr[0].x
interface = 0;
calculate
{ arr[1].x = 1;
arr[2].x
void cal(int= item);
2;
} for (int i = 0; i < 3; ++i)
arr[i].show();
class display implements calculate
{ }
} int x;
public void cal(int item)
What will be the output of the following Java program?
interface
What will becalculate
the output of the following Java program?
{
void cal(int
interface calculateitem);
{ }
classint displayA
VAR = implements
0; calculate
{ void cal(int item);
Which intof x; the following access specifiers can be used for an interface?
}
public void cal(int
class display item) calculate
implements
Which {{ of the following is the correct way of implementing an interface A by class B?
xint= x;
item * item;
} public void cal(int item)
} {
classtype
What displayB implements
of variable
if (item<2) can becalculate
defined in an interface?
{ x = VAR;
int x;else
Whatpublic
does void an interface
cal(int contain?
item)
x = item * item;
{ }
} x = item / item;
class } interfaces
What
} type of methods an interface contain by default?
{
class interfaces
{ happens
What public staticwhen a constructor
void main(Stringisargs[])
defined for an interface?
public
{ static void main(String args[])
{ display[] arr=new display[3];
displayA arr1 = new displayA;
displayB arr2 = new displayB;
for(int i=0;i<3;i++)
arr1.x = 0; display();
arr[i]=new
What happens
arr2.x when we access the same variable defined in two interfaces impleme
= 0;
arr[0].cal(0);
arr1.cal(2);
arr[1].cal(1);
arr2.cal(2);
arr[2].cal(2);
System.out.print(arr1.x
Can “abstract” keyword be used
System.out.print(arr[0].x+" + "with
" +" arr2.x);
+constructor,
arr[1].x + " Initialization
" + arr[2].x); Block, Instance Initiali
} }
} }

 JUnits are used for which type of testing?

Which of the below is an incorrect annotation with respect to JUnits?

Which method is used to verify the actual and expected results in Junits?

How to let junits know that they need to be run using PowerMock?
How can we simulate if then behavior in Junits?

What is used to inject mock fields into the tested object automatically?

How can junits be implemented using maven?

Which of the following is not introduced with Java 8?

What is the purpose of BooleanSupplier function interface?

What is the return type of lambda expression?

Which is the new method introduced in java 8 to iterate over a collection?

What are the two types of Streams offered by java 8?

Which of the following is not a core interface of Hibernate?

SessionFactory is a thread-safe object

Which of the following methods returns proxy object?

Which of the following methods hits database always?


Which of the following method is used inside session only?

Which of the following is not a state of object in Hibernate?

In which file database table configuration is stored?


Option A Option B Option C
-128 to 127 0 to 256 0 to 32767
ASCII ISO-LATIN-1 UNICODE
True & False 0&1 Any integer value
characters in Java?
boolean b1 = 1; boolean b2 = ‘false’; boolean b3 = false;
Ascending order Descending order Random order
1 0

0 1 2

Sorted in the order of declaration of


Enums Sorted in alphabetical order of Enums Sorted based on order() method

Runtime Error Compilation Error It runs successfully

Runtime Error EnumNotDefined Exception It runs successfully

getEnums() getEnumConstants() getEnumList()


Syntax Memory usage Garbage creation
int float double

0.00999999999999999
0.01 0.01 0.01
0.00999999999999999 0.01

SimpleDateFormat DateFormat SimpleFormat

SimpleDateFormat sdf = new SimpleDateFormat sdf = new SimpleDateFormat sdf = new


SimpleDateFormat("yyyy-mm-dd"); SimpleDateFormat("yyyy-mm-dd"); SimpleDateFormat("yyyy-mm-
sdf.parse(new Date()); sdf.format(new Date()); dd");
new Date().parse();
SimpleDateFormat sdf = new SimpleDateFormat sdf = new SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-mm-
SimpleDateFormat("yyyy-mm-dd"); SimpleDateFormat("yyyy-mm-dd"); dd");
sdf.parse(new Date()); sdf.format(new Date()); new Date().parse();
1 0
useDaylightTime() of TimeZone
useDaylightTime() of Time class useDaylightTime() of Date class class
java.sql.Date  java.util.Date java.sql.DateTime

long diffInMilli = long diffInMilli = Date diffInMilli =


java.time.Duration.between java.time.difference(dateTime1, java.time.Duration.between(date
(dateTime1, dateTime2).toMillis(); dateTime2).toMillis(); Time1, dateTime2).toMillis();

38 39 40

02468 12345 0123456789

5656 565 Runtime error

“Hello World”  “Hello\nWorld”  “\”Hello World\””

b cannot contain value 100, limited by its * operator has converted b * 50 into
range int, which can not be converted to b cannot contain value 50
byte without casting

long int double

EU UE VE

38 43 39 44 295 300
b is : 2 b is : 1 Compilation Error

1 1 1 0 1 0 3

int arr[] = new int[5] int [] arr = new int[5] int arr[] = new int[5]

It is necessary to use new operator to Array can be initialized using comma Array can be initialized when they
initialize an array separated expressions surrounded by are declared
curly braces

ArrayList Abstract class Object class

3 0 4

[A, D, C] [A, B, C] [A, B, C, D]

truetrue falsefalse 1

Protected Void Public

Memory address of allocated memory of NULL Any arbitrary pointer


object

class struct int


Box obj = new Box(); Box obj = new Box; obj = new Box();

malloc alloc new

 Every class must contain a main() Applets do not require a main() There can be only one main()
method method at all method in a program

Public method is accessible to all other Public method is accessible only to Public method can only be called
classes in the hierarchy subclasses of its parent class by object of its class

int float void

Function overriding Function overloading Function doubling

finalize delete class

main method finalize method static method

All object of a class are allotted memory If a function is defined public it can
for the all the variables defined in the be accessed by object of other class main() method must be made
public
class by inheritation

int float void

import catch abstract

finalize delete class

delete free new

finalize() delete() main()


finalize() method is called when a
default constructor is called at the time constructor can be parameterized object goes out of scope and is no
of object declaration
longer needed
Private constructor ensures only one Private constructor ensures multiple
instance of a class exist at any point of instances of a class exist at any point Private constructor eases the
time of time instantiation of a class

Runtime Error Throws exception compile time error

Constructors cannot be synchronized in Java does not provide default copy Constructor can have a return
Java constructor type

Class.getInstance is same as new  Class.getInstance needs to have


Class.getInstance calls the constructor operator matching constructor

It can contain return type It can take any number of parameters It can have any non access
modifiers

1 0

Protected constructor can be called Protected constructor can only be Protected constructor can be
directly called using super() used outside package

Calling another constructor in Referring to the instance variable


Passing itself to another method when local variable has the same
constructor chaining name

Compilation error Compilation succeeds Runtime error

Compilation error Runtime error Compilation and runs successfully

Heap Stack JVM

Young space Old space JVM

Cleanup model Mark and sweep model Space management model

Initial; Maximum memory Maximum; Initial memory Maximum memory


MemoryFullException MemoryOutOfBoundsException OutOfMemoryError

jmap memorymap memorypath

The thread continues its operation Garbage collection cannot happen The thread is paused while
until the thread is running garbage collection runs

JVM JConsole JProfiler

Code changes JVM parameter tuning Process restart

1 0

method overloading method overriding method hiding

Methods Constructors All of the mentioned

Copy of argument is made into


Copy of argument is made into the Reference to original argument is the formal parameter of the
formal parameter of the subroutine passed to formal parameter of the subroutine and changes made on
subroutine parameters of subroutine have
effect on original argument

Polymorphism Abstraction Encapsulation

private public protected

public private static

private public public, within its own package

Polymorphism Abstraction Encapsulation


private members of class can be
public members of class can be accessed private members of class can only be inherited by a subclass, and
by any code in the program accessed by other members of the become protected members in
class subclass
public private protected
public private protected

private public protected

private public protected

accessible within package and


accessible only within the class accessible only within package outside the package but through
inheritance only

Any class can instantiate objects of class Objects of class A can be instantiated Inherited class can instantiate
A only within the class where it is objects of class A
declared

default and final default and static  public, static and final

Final class cause compilation failure Final class cannot be instantiated Final class cause runtime failure

1, 10 10, 10 10 1

1 0

protected private public

class object variable

final last constant

class object variable

static methods can call other static static methods must only access  static methods can not refer to
methods only static data this or super in any way
Variables declared as final occupy  final variable must be initialized at  Arrays in java are implemented
memory the time of declaration as an object

main() delete() run()

class object variable


char() Charat() charat()

upper super this

 isequal() isequals() equal()

Every string is an object of class


String is a class Strings in java are mutable String

main method finalize method static method

Function overriding Function overloading Function doubling

Parameters data type Number of parameters Return type of method


void int float

Any already defined method in


Two or more methods with same name Two or more method having same
can be differentiated on the basis of name can be differentiated on basis java library can be defined again
their parameters data type of number of parameters in the program with different data
type of parameters

Recursion is a process of defining a Recursion is a process of defining


Recursion is a class method that calls other methods a method that calls itself
repeatedly repeatedly

Array Stack Queue

System stops the program after some After 1000000 calls it will be
An infinite loop occurs time automatically stopped

super this extent


Method overloading Method overriding Method hiding

static constant protected


super(void); superclass.(); super.A();
 final, native, private  final, static, protected final, private, abstract
Abstraction Encapsulation Polymorphism

2 3 7

String class Object class Abstract class


Objectcopy() copy() Object clone()
get() void getclass() Class getclass()

Super Const Class

abstract extends abstract and extends


Object class abstract class ArrayList class

0 2 Runtime error

abst abstract Abstract


Thread AbstractList List

Abstract A simple class Static class

safe mode  debug mode successfully run mode


java.util java.lang ArrayList

+ = &
get() Sizeof() lengthof()
CHARAT() chatat() charAt()
String() String(void) String(0)

String objects are immutable, they canno String object can point to some other rStringBuffer class is used to store st

H Hello

Runtime Error

0 36 Runtime error

Generic methods are the methods definedGeneric


i methods are the methods thatGeneric methods are methods that

Type Interface Interface Inner class


Run Time Compilation Time Can Occur Any Time

try finally thrown


try finally thrown

try
finally thrown

Hello World HelloWorld

String RuntimeExceptions Throwable


Error Exception RuntimeExecption

Error Exception RuntimeExecption

ArithmeticException ClassNotFoundException NullPointerException

Hello World Compilation Error


try finally throw
Error Exception Throwable

new malloc alloc

TypeA TypeB Compile Time Error


A B Hello

Finally Compilation fails The code runs with no output

throws finally throw

finally catch finally & catch


ArithmeticException MathException IllegalAccessException

ArithmeticException ArrayException ArrayIndexException


It allows us to manually handle the exceptIt allows to fix errors It prevents automatic terminating
try catch throw

try catch throw


try catch throw

try block need not to be followed by catchtry block can be followed by finally blotry can be followed by both catch a
Hello World HelloWOrld

Hello World HelloWOrld

Hello World HelloWOrld

Hello World HelloWOrld

Exception Throwable Abstract

getException() getMessage() obtainDescription()


obtainStackTrace() printStackTrace() getStackTrace()
Throwable System RunTime
3
Exception Runtime Error
3
Exception Runtime Error

A B Complilation Error

3 Exception Runtime error


TypeA TypeB Compilation Error

stop() sleep() join()

run() Alive()  isAlive()

0 & 256 0&1 1 & 10


sleep()  isAlive()  join()

set() make() setPriority()

It’s a process of handling situations whe It’s a process by which many thread arIt’s a process by which a method is

My Thread Thread[My Thread,5,main] Compilation Error

My Thread Thread[My Thread,5,main] Exception

0 1 1

1 0

truetrue

stop() run() runThread()


run() start() runThread()

A thread can be formed by implementing R


A thread can be formed by a class thatstart() method is used to begin exe
My Thread Thread[My Thread,5,main] Compilation Error

My Thread Thread[My Thread,5,main] Compilation Error

My Thread Thread[My Thread,5,main] Compilation Error

Thread[New Thread,0,main] Thread[New Thread,1,main] Thread[New Thread,5,main]

1 0 truetrue
get() ThreadPriority() getPriority()
sleep() terminate() suspend()

isAlive() Join() isRunning()

Thread[5,main] Thread[New Thread,5] Thread[main,5,main]

main Thread New Thread

0 1 4

0 1 1

It’s a process in which two different proc It’s a process in which two or more pa It’s a process in which many differ

Process based Thread based Process and Thread based

Integer Float double

Anyone will be executed first lexographicaBoth of them will be executed simulta None of them will be executed

By multithreading CPU idle time is minimi By multitasking CPU idle time is minim Two thread in Java can have the sa
Thread[5,main] Thread[main,5] Thread[main,0]
4 5 0

main Thread System

Thread Process Thread and Process

Process Daemon Thread User Thread

Process Process scheduler Thread

1 0

Avoid using multiple threads Avoid hold several locks at once Execute foreign code while holding

run() method calls start() method and runrun() method creates new thread run() method can be called directly

Thread(Runnable a, String str) Thread(int priority) Thread(Runnable a, int priority)

Calling SetPriority() method on a Thread o Calling notify() method on an object Calling wait() method on an object

yield() notify() wait()

synchronize syn synch

wait() notify() notifyAll()

wait() notify() notifyAll()

1 0 Main thread interrupted

1 0 Main thread interrupted


1 0 Main thread interrupted

All Window Tools All Writing Tools Abstract Window Toolkit

streams Variables classes

Integer stream Short stream Byte stream

InputStream InputOutputStream Reader

InputStream Writer ReadStream

abcqfgh abc abcq

abc’ abcdef/’ abc’def/’egh


4 5 6

IOException InterruptedException SystemException

get() getLine() read()

BufferedReader StringReader BufferedStreamReader

Hello Hello stop World

Hello World Helloworld

Pattern class matcher class PatternSyntaxException

interpretes pattern in the string Performs match in the string interpreted both pattern and perfo

Pattern class Matcher class PatternSyntaxException

Replace all characters that matches patterReplace first subsequence that matchesReplace all other than first subseq

An event is an object that describes a stat An event is an object that describes a An event is an object that describ
KeyListener() addKistener() addKeyListener()
java.io  java.lang java.net

getID()  getSource() getEvent()

EventObject EventClass ActionEvent

ActionEvent ComponentEvent AdjustmentEvent

ActionEvent ComponentEvent AdjustmentEvent


getCommand() getActionCommand() getActionEvent()

getKey() getModifier() getActionKey()


ActionEvent KeyEvent WindowEvent

ComponentEvent ContainerEvent FocusEvent


getContainer() getContainerCommand() getActionEvent()

TextEvent MouseEvent FocusEvent

getPoint() getCoordinates() getMouseXY()

Object Packages Interfaces

Public Protected No Modifier


Public Protected Private

import pkg. Import pkg. import pkg.*


0 1 2

xello xxxxx Hxllo


Objects Packages Interfaces

Public Protected private


class manager extends salary {} class manager implements salary {} class manager imports salary {}
0 2 4
00 22 41

012 0 2 4 0 0 4

Protected Private Public

class B extends A{} class B implements A{} class B imports A{}

public static private final public final

Method definition Method declaration Method declaration and definition

abstract static final

Compilation failure Runtime Exception The interface compiles successfully

Compilation failure Runtime Exception The JVM is not able to identify the

1 0

Unit Testing Integration Testing System Testing

@Test @BeforeClass @Junit

assert() equals() ==

@PowerMock @RunWith(PowerMock) @RunWith(Junits)


if{..} else{..}  if(..){..} else{..} Mockito.when(…).thenReturn(…

@InjectMocks @Inject @InjectMockObject

<dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.junit</groupId> <groupId>mock.junit</groupId
<artifactId>junit</artifactId> <artifactId>junit</artifactId> >
<version>4.8.1</version> <version>4.8.1</version> <artifactId>junit</artifactId>
</dependency> </dependency> <version>4.8.1</version>
</dependency>

Stream API Serialization Spliterator

represents supplier of Boolean-valuedreturns Boolean-valued result There is no such function interf

String Object void

for (String i : StringList) foreach (String i : StringList) StringList.forEach()

sequential and parallel sequential and random parallel and random

Configuration Criteria SessionManagement

1 0

loadDatabase() getDatabase() load()

load() loadDatabase() getDatabase()


merge() update() end()

Attached() Detached() Persistent()

.dbm .hbm .ora


Option D Answer Explanation
0 to 65535 D
None of the mentioned C
1 A

boolean b4 = ‘true’ C
Depends on the order() method D
B

3 A

Sorted in descending order of names of


Enums A

EnumNotDefined Exception B

Compilation Error D

getEnum() B
Precision D
Bigdecimal D

0.009999999999999998 A
0.009999999999999998

DateConverter A

SimpleDateFormat sdf = new


SimpleDateFormat("yyyy-mm-dd"); B
new Date().format();
SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-mm-dd"); A
new Date().format();

useDaylightTime() of DateTime class C

 java.util.DateTime A

Time diffInMilli =
java.time.Duration.between(dateTime1, A
dateTime2).toMillis();

41 C

1 2 3 4 5 6 7 8 9 10 B

Compilation error D

"Hello All string literals must begin


world" D and end in the same line.

No error in this code While evaluating an expression containing int, bytes


or shorts, the whole expression is converted to int
B then evaluated and the result is also of type int
float If any operand is double the result of an expression
C is double

UF A

B Type casting a larger variable into a smaller variable


results in modulo of larger variable by range of
smaller variable. b contains 300 which is larger than
byte’s range i:e -128 to 127 hence d contains 300
modulo 256 i:e 44.
295.04 300
The code does not compile because the method
An exception is thrown at runtime calculate() in class A is final and so cannot be
overridden by method of class b.

In argument[0] = args;, the reference variable


1 2 3 D arg[0], which was referring to an array with two
elements, is reassigned to an array (args) with three
elements

int arr[] = int [5] new D Operator new must be succeeded by array type and
array size.
Array can be initialized using both new and comma
separated expressions surrounded by curly braces
None of the mentioned A example : int arr[5] = new int[5]; and int arr[] = { 0,
1, 2, 3, 4};

String Object class is superclass of every class in Java


C

3 ciel(double X) returns the smallest whole number


greater than or equal to variable x.
C
obj is an object of class ArrayLists 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
[A, D, B, C] D stored at that position by 1

This program was previously done by using


Runnable interface, here we have used Thread
class. This shows both the method are equivalent,
0 B we can use any of them to create a thread

Public, private, protected and default are the access


Private modifiers.
B
Memory is allocated to an object using new
operator. box obj; just declares a reference to
object, no memory is allocated to it hence it points
Garbage B to NULL
none of the mentioned A
 new Box obj; A
Operator new dynamically allocates memory for an
give C object and returns a reference to it. This reference
is address in memory of the object allocated by
new.
Every class does not need to have a main() method,
 main() method must be made public A there can be only one main() method which is made
public.
Public method can be accessed by calling
object of the public class A

Return type of a method must be made void if it is


double C
not returning any value.

Function overloading is a process of defining more


than one method in a class with same name
differentiated by function signature i:e return type
None of the mentioned B or parameters type and number. Example – int
volume(int length, int width) & int volume(int
length , int width , int height) can be used to
calculate volume.

A constructor is a method that initializes an object


constructor D immediately upon creation. It has the same name
as that of class in which it resides
main() method can be defined only once in a
private method A program. Program execution begins from the main()
method by java runtime system

All object of class share a single copy of methods


defined in a class, Methods are allotted memory
All object of a class are allotted memory for D only once. All the objects of the class have access to
the methods defined in the class
methods of that class are allotted memory only for
the variables not for the methods.

Constructors does not have any return type, not


None of the mentioned D even void.
this keyword can be used inside any method to
refer to the current object. this is always a
this D reference to the object on which the method was
invoked.
A constructor is a method that initializes an object
constructor D immediately upon creation. It has the same name
as that of class in which it resides.

 Java handles deallocation of memory


automatically, we do not need to explicitly delete
an element. Garbage collection only occurs during
None of the mentioned D execution of the program. When no references to
the object exist, that object is assumed to be no
longer needed, and the memory occupied by the
object can be reclaimed.

None of the mentioned A


 finalize() method is called just prior to garbage
finalize() method must be declared protected C collection. it is not called when object goes out of
scope.
Object of private constructor can only be created
Private constructor allows creating objects in A within class. Private constructor is used in singleton
other classes pattern

Runs successfully C this() and super() cannot be used in a method. This


throws compile time error

 “this” and “super” can be used in a The constructor cannot have a return type. It should
C create and return new objects. Hence it would give
constructor a compilation error.
Class.getInstance creates object if class does Class class provides list of methods for use like
not have any constructor D getInstance().
Constructor returns a new object with variables
 Constructor cannot throw an exception B defined as in the class. Instance variables are newly
created and only one copy of static variables are
created.

B No instance can be created of abstract class. Only


pointer can hold instance of object.

Protected access modifier means that constructor


protected constructor can be instantiated B can be accessed by child classes of the parent class
even if child is in a different package
and classes in the same package.

“this” is an important keyword in java. It helps to


Passing itself to method of the same class D distinguish between local variable and variables
passed in the method as parameters.
Compilation succeeds but at the time of
creating object using default constructor, it D
throws compilation error
The constructor cannot have a return type. It should
Only String return type is allowed A create and return new object. Hence it would give
compilation error.

Class C JVM is the super set which contains heap, stack,


objects, pointers, etc.

A new object is always created in young space.


Once young space is full, a special young collection
A is run where objects which have lived long enough
are moved to old space and memory is freed up in
young space for new objects.

A mark and sweep garbage collection consists of


two phases, the mark phase and the sweep phase. I
mark phase all the objects reachable by java
threads, native handles and other root sources are
Sweep model B marked alive and others are garbage. In sweep
phase, the heap is traversed to find gaps between
live objects and the gaps are marked free list used
for allocating memory to new objects

JVM will be started with Xms amount of memory


Initial memory A and will be able to use a maximum of Xmx amount
of memory. java -Xmx2048m -Xms256m.
The Xms flag has no default value, and Xmx typically
has a default value of 256MB. A common use for
MemoryError C these flags is when you encounter a
java.lang.OutOfMemoryError.
jvmmap A We can use jmap as jmap -J-d64 -heap pid.

The thread and garbage collection do not C The thread is paused when garbage collection runs
interfere with each other which slows the application performance.

Memory leak is like holding a strong reference to an


object although it would never be needed anymore.
Eclipse Profiler A Objects that are reachable but not live are
considered memory leaks. Various tools help us to
identify memory leaks.

Process restart is not a permanent fix to memory


GC parameter tuning C leak problem. The problem will resurge again

Garbage Collection cannot be controlled by a


B program.

Two or more methods can have same name as long


as their parameters declaration is different, the
none of the mentioned A methods are said to be overloaded and process is
called method overloading. Method overloading is a
way by which Java implements polymorphism

None of the mentioned C

Reference to original argument is passed to When we pass an argument by call-by-value a copy


formal parameter of the subroutine and of argument is made into the formal parameter of
changes made on parameters of subroutine A the subroutine and changes made on parameters of
subroutine have no effect on original argument,
have effect on original argument they remain the same

Recursion D

main() method must be specified public as it called


by Java run time system, outside of the program. If
none of the mentioned B no access specifier is used then by default member
is public within its own package & cannot be
accessed by Java run time system.

protected C

When we pass an argument by call-by-value a copy


of argument is made into the formal parameter of
protected A the subroutine and changes made on parameters of
subroutine have no effect on original argument,
they remain the same.

Recursion C

protected members of a class can be private members of a class can not be inherited by
inherited by a subclass, and become private C a subclass.
members of the subclass

None of the mentioned A


Public, private, protected and default are the access
void D modifiers.
 The variables should be private and should be
default A accessed with get and set methods.

default A Private variables are accessible only within the


class.

The protected access modifier is accessible within


package and outside the package but only through
accessible by all C inheritance. The protected access modifier can be
used with data member, method and constructor. It
cannot be applied in the class.

classes within the same package as class A If we make any class constructor private, we cannot
can instantiate objects of class A B create the instance of that class from outside the
class.

Variables of an interface are public, static and final


by default because the interfaces cannot be
protect, static and final C instantiated, final ensures the value assigned
cannot be changed with the implementing class and
public for it to be accessible by all the implementing
classes

Final class cannot be inherited. This helps when we


Final class cannot be inherited D do not want classes to provide extension to these
classes.

Only one copy of static variables are created when a


11 A class is loaded. Each object instantiated has its own
copy of instance variables.

Protected class member (method or variable) is like


package-private (default visibility), except that it
B also can be accessed from subclasses. Since there is
no such concept as ‘subpackage’ or ‘package-
inheritance’ in Java, declaring class protected or
package-private would be the same thing.

Default is the access modifier when none is defined


default D explicitly. It means the member (method or
variable) can be accessed within the same package.

none of the mentioned B

A variable can be declared final, doing so prevents


static A its content from being modified. Final variables
must be initialized when it is declared.

method B static statements are run as soon as class containing


then is loaded, prior to any object declaration

All objects of class share same static variable, when


when object of class is declared, each object D object of a class are declared, all the objects share
contains its own copy of static variables same copy of static members, no copy of static
variables are made.
All arrays contain an attribute-length which
contains the number of elements stored in A
the array
main() method must be declared static, main()
finalize() A method is called by Java runtime system before any
object of any class exists.
character array A
charAt() D
Whenever a subclass needs to refer to its
none of the mentioned B immediate superclass, it can do so by use of the
keyword super.
equals() D

 Java defines a peer class of String, called Strings in Java are immutable that is they can not be
StringBuffer, which allows string to be altered B modified.

private method C If a static method is present in the program then it


will be executed first, then main will be executed.

Function overloading is a process of defining more


than one method in a class with same name
differentiated by function signature i:e return type
None of the mentioned B or parameters type and number. Example – int
volume(int length, int width) & int volume(int
length , int width , int height) can be used to
calculate volume.

All of the mentioned D


both int and float D

If a method is returning a value the calling Even if a method is returning a value, it is not
statement must have a variable to store that D
value necessary to store that value.

Recursion is a process of defining a method Recursion is the process of defining something in


that calls other methods which in turn call C terms of itself. It allows us to define a method that
again this method calls itself.

Tree B  Recursions are always managed by using stack

If a recursive method does not have a base case


None of the mentioned A then an infinite loop occurs which results in Stack
Overflow.
extends A
None of the mentioned B

To disallow a method from being overridden,


specify final as a modifier at the start of its
declaration. Methods declared as final cannot be
final D overridden
super(); D
Every interface variable is implicitly public static and
final, static, public D final.
None of the mentioned C

Compilation error

C Both x,and y are pointing to the same array.

ArrayList class B Object class is superclass of every class in Java.


clone() C
None of the mentioned C

Final Declaring a class final implicitly declared all of its


D methods final, and makes the class inheritable.

A abstract class is incomplete by itself and relies


upon its subclasses to provide a complete
implementation. If we declare a class final then no
class can inherit that class, an abstract class needs
its subclasses hence both final and abstract cannot
none of the mentioned A be used for a same class.
None of the mentioned B
class A is an abstract class, it contains a abstract
function display(), the full implementation of
Compilation error display() method is given in its subclass B, Both the
display functions are the same. Prototype of
display() is defined in class A and its
implementation is given in class B.
B
abstract class B
None of the Mentioned A
Any subclass of an abstract class must either
implement all of the abstract method in the
None of the mentioned A superclass or be itself declared abstract
Debug mode allows us to run program interactively
while watching source code and variables during
exception mode B execution.
None of the mentioned B
Operator + is used to concatenate strings, Example
|| String s = “i ” + “like ” + “java”; String s contains “I
A like java”.
Method length() of string class is used to get the
 length() D length of the object which invoked method length().
ChatAt() C
None of the mentioned A
StringBuffer class is used to create strings that can
None of the mentioned C be modified after they are created.

Compilation Error B

Complilation Error

Generic methods are methods that introduce their


own type parameters. This is similar to declaring a
generic type, but the type parameter scope is
limited to the method where it is declared. Static
and non-static generic methods are allowed, as well
Generic methods are methods that take void C as generic class constructors.
Type inference, allows you to invoke a generic
method as an ordinary method, without specifying
All of the mentioned A a type between angle brackets.
None of the mentioned A Exceptions in Java are run-time errors.

Exceptional handling is managed via 5 keywords –


catch C try, catch, throws, throw and finally.
catch A

If an exception occurs within the try block, it is


catch D thrown and cached by catch block for processing.

System.ou.print() function first converts the whole


parameters into a string and then prints, before
“Hello” goes to output stream 1 / 0 error is
encountered which is cached by catch block printing
Hello World B just “World”.
All the exception types are subclasses of the built in
Cacheable C class Throwable.
Error class is related to java run time error that
can’t be caught usually, RuntimeExecption is
subclass of Exception class which contains all the
All of the mentioned B exceptions that can be caught.

Error class is related to java run time error that


can’t be caught usually, RuntimeExecption is
subclass of Exception class which contains all the
All of the mentioned A exceptions that can be caught.
parseInt() method parses input into integer. The
exception thrown by this method is
NumberFormatException D NumberFormatException.

First Exception then World D


catch C
Throw C

new is used to create an instance of an exception.


All of java’s built in run-time exceptions have two
constructors: one with no parameters and one that
thrown A takes a string parameter.

0TypeB C Because we can’t go beyond array limit


RunTime Error

An exception is thrown at runtime A Because finally will execute always.


finally keyword is used to define a set of
instructions that will be executed irrespective of the
catch B exception found or not.

try block can be followed by any of finally or catch


block, try block checks for exceptions and work is
performed by finally and catch block as per the
none of the mentioned C exception.
IllegarException A

ArrayIndexOutOfBoundsException is a built in
exception that is caused when we try to access an
index location which is beyond the length of an
ArrayIndexOutOfBoundsException D array.
All of the mentioned D
check try is used for the block that needs to checked for
A exception.
check B
check C

try need not to be followed by anything D try must be followed by either catch or finally block
Compilation Error B

Compilation Error A

Compilation Error D

Compilation Error C

System A
getMessage() returns a description of the
obtainException() B exception.
displayStackTrace() B
Class A

Compilation Error B Myexception is self defined exception.


Mexception is self defined exception, we are
generating Myexception but catching
 Compilation Error C DevideByZeroException
try block is throwing NullPointerException
which causes error.but the
catch block is used to counter Arithmetic Exception.
RunTime Error Hence NullPointerException occurs since no catch is
C there which can handle it, compilation error occurs.

Complilation Error

B Myexception is self defined exception.


Runtime Error C try without catch or finally
By calling sleep() within main(), with long enough
delay to ensure that all child threads terminate
call() B prior to the main thread
The isAlive( ) method returns true if the thread
upon which it is called is still running. It returns
checkRun() C false otherwise.

1 & 256 C
 stop() C

The default value of priority given to a thread is 5


but we can explicitly change that value between the
permitted values 1 & 10, this is done by using the
makePriority() C When
methodtwo or more threads need to access the
setPriority().
same shared resource, they need some way to
ensure that the resource will be used by only one
thread at a time, the process by which this is
It’s a method that allow too many threads to A achieved is called synchronization

Although we have not created any object of thread


class still we can make a thread pointing to main
Runtime Error B method, we can refer it by using this

 join() method of Thread class waits for thread


Runtime Error being called to finish or terminate, but here we
have no condition which can terminate the thread,
hence code ‘t.join()’ leads to runtime error and
D nothing will be printed on the screen.

0 isAlive() method is used to check whether the


thread being called is running or not, here thread is
the main() method which is running till the program
C is terminated hence it returns true.

This program was previously done by using


Runnable interface, here we have used Thread
class. This shows both the method are equivalent,
falsefalse D we can use any of them to create a thread

To implement Runnable interface, a class needs


stopThread() B only to implement a single method called run()
startThread() B

run() method is used to define the code that


constitutes the new thread, it contains the code to
be executed. start() method is used to begin
execution of the thread that is execution of run().
run() itself is never used for starting execution of
run() method is used to begin execution of a t D the thread
Runtime Error A

Runtime Error B Thread t has been made by using Runnable


interface, hence it is necessary to use inherited
abstract method run() method to specify
instructions to be implemented on the thread, since
Runtime Error C Thread
no run()t method
has beenismade
used itwith default
gives priority value
a compilation error
5 but in run
Threads t1 &method the priority
t2 are created has newthread
by class been explicitly
that
changed to MAX_PRIORITY
is implementing of class thread,
runnable interface, that isthe
hence both
10 by code
threads are‘t.setPriority(Thread.MAX_PRIORITY);’
provided their own run() method
Thread[New Thread,10,main] D using the setPriority
specifying the actionsfunction of thread
to be taken. Whent.
constructor of newthread class is called first the
run() method of t1 executes than the run method of
t2 printing 2 times “false” as both the threads are
not equal one is having different priority than other,
falsefalse D hence falsefalse is printed.
getThreadPriority() C
stop() A

isAlive() function is defined in class Thread, it is


used for implementing multithreading and to check
whether the thread called upon is still running or
Alive() A not.

Thread[New Thread,5,main] D

The getName() function is used to obtain the name


of the thread, in this code the name given to thread
Thread[New Thread,5,main] C is ‘New Thread’.

5
D The default priority given to a thread is 5.

Thread t is seeded to currently program, hence


0 when you run the program the thread becomes
C active & code ‘t.isAlive’ returns true.
Multithreaded programming a process in which two
or more parts of the same process run
It’s a process in which a single process can a B simultaneously.

There are two types of multitasking: Process based


None of the mentioned C multitasking and Thread based multitasking
Java assigns to each thread a priority that
determines hoe that thread should be treated with
respect to others. Thread priority is integers that
long A specify
In casesrelative priority
where two of one
or more thread
thread to another.
with same
priority are competing for CPU cycles, different
operating system handle this situation differently.
Some execute them in time sliced manner some
It is dependent on the operating system D depending on the thread they call.
Thread exist in several states, a thread can be
running, suspended, blocked, terminated & ready
A thread can exist only in two states, running D to run.
The output of program is Thread[main,5,main], in
Thread[main,5,main] D this priority assigned to the thread is 5. It’s the
default value. Since we have not named the thread
1 they are named by the group to they belong i:e
B main method.
The output of program is Thread[main,5,main],
Since we have not explicitly named the thread they
are named by the group to they belong i:e main
None of the mentioned A method. Hence they are named ‘main’.
Thread is a lightweight and requires less resources
to create and exist in the process. Thread shares the
Neither Thread nor Process A process resources.
Daemon thread runs in the background and does
not prevent JVM from terminating. Child of daemon
JVM Thread B thread is also daemon thread

Thread scheduler decides the priority of the thread


execution. This cannot guarantee that higher
priority thread will be executed first, it depends on
thread scheduler implementation that is OS
Thread scheduler D dependent.
Deadlock is java programming situation where one
thread waits for an object lock that is acquired by
A other thread and vice-versa.

To avoid deadlock situation in Java programming do


Use interruptible locks C not execute foreign code while holding a lock.
start() eventually calls run() method. Start() method
creates thread and calls the code written inside run
start() method creates new thread and calls c D method.

Thread(Runnable a, String str) is a valid constructor


Thread(Runnable a, ThreadGroup t) A for thread. Thread() is also a valid constructor.
notify() wakes up a single thread which is waiting
Calling read() method on an InputStream obje B for this object.
wait() always causes the current thread to go into
the object’s wait pool. Hence, using this in a thread
Thread.killThread() C will keep it in running state.
Polling is a usually implemented by looping in CPU
is wastes CPU time, one thread being executed
synchronized D depends on other thread output and the other
thread depends on the response on the data given
to the first thread. In such situation CPU time is
wasted, in Java this is avoided by using methods
all of the mentioned D wait(), notify() and notifyAll().
wait() method is used to tell the calling thread to
give up a monitor and go to sleep until some other
thread enters the same monitor. This helps in
sleep() A avoiding polling and minimizes CPU idle time.
obj1.t.wait() causes main thread to go out of
processing in sleep state hence causes exception
None of the mentioned C and “Main thread interrupted” is printed

Thread.sleep(1000) has caused all the threads to be


suspended for some time, hence onj1.t.isAlive()
None of the mentioned B returns false.
Both obj1 and obj2 have threads with different
name that is “one” and “two” hence
None of the mentioned B obj1.t.equals(obj2.t) returns false
AWT stands for Abstract Window Toolkit, it is used
Abstract Writing Toolkit C by applets to interact with the user.
Like in any other language, streams are used for
Methods A input and output operations.
Java defines only two types of streams – Byte
Long stream C stream and character stream

Byte stream uses InputStream and OutputStream


All of the mentioned A classes for input and output operation.
Character streams uses Writer and Reader classes
InputOutputStream B for input & output operations.

abcqfghq C

abcqfghq A \’ is used for single quotes that is for representing ‘ .


7  length() method is used to obtain length of
B StringBuffer object, length of “Hello” is 5.

SystemInputException A read method throws IOException

readLine() C

InputStreamReader A

“stop” will be able to terminate the do-while loop


only when it occurs singly in a line. “Hello stop
Hello stop World D World” does not terminate the loop.

append() method of class StringBuffer is used to


concatenate the string representation to the end of
Hello World D invoking string.
java.util.regex consists 3 classes.
PatternSyntaxException indicates syntax error in
Regex class D regex
macther() method is invoked using matcher object
which interpretes pattern and performs match
 None of the mentioned. C operations in the input string
object of Pattern class can represent compiled
None of the mentioned A regular expression
replaceAll method replaces every subsequence of
the sequence that matches pattern with a
Replace every subsequence of the input seque D replacement string
An event is an object that describes a state change
An event is a class used for defining object, to A in a source.
eventKeyboardListener() C
java.util D
getID() can be used to determine the type of an
getEventObject() A event.
EventObject class is a super class of all the events
ItemEvent A and is defined in java.util package
AdjustmentEvent is generated when a scroll bar is
WindowEvent C manipulated
WindowEvent is generated when a window is
activated, closed, deactivated, deiconfied, iconfied,
WindowEvent D opened or quit
 getActionEventCommand() B

The getModifiers() methods returns a value that


indicates which modifiers keys (ALT, CTRL, META,
getActionEvent() B SHIFT) were pressed when the event was generated
AdjustmentEvent D

A ComponentEvent is generated when the size,


InputEvent A position or visibility of a component is changed
getContainerEvent() D
A WindowEvent is generated when a window is
WindowEvent D opened, close, activated or deactivated

getPoint() method can be used to obtain


coordinates of a mouse, alternatively we can use
getX() and getY() methods for x and y coordinates of
getMouseCordinates() A mouse respectively

Packages are both naming and visibility control


mechanism. We can define a class inside a package
None of the Mentioned B which is not accessible by code outside the package
Either we can use public, protected or we can name
All of the mentioned D the class without any specifier
No Modifier A

Import pkg.* C Operator * is used to import the entire package


012
C

Hexlo C
None of the Mentioned C

Access specifier of an interface is either public or no


specifier. When no access specifier is used then
default access specifier is used due to which
interface is available only to other members of the
package in which it is declared, when declared
All of the mentioned A public it can be used by any code
none of the mentioned B

None of the mentioned C


class displayA implements the interface calculate by
doubling the value of item, where as class displayB
implements the interface by dividing item by item,
1 4 therefore variable x of class displayA stores 4 and
C variable x of class displayB stores 1
0 1 4
C
Interface can have either public access specifier or
no specifier. The reason is they need to be
Public, protected, private A implemented by other classes.
Concrete class implements an interface. They can
None of the mentioned B be instantiated

variable defined in an interface is implicitly final and


static final D static. They are usually written in capital letters
Interface contains the only declaration of the
 Method name B method.
By default, interface contains abstract methods.
The abstract methods need to be implemented by
private A concrete classes
Constructor is not provided by interface as objects
The implementing class will throw exception A cannot be instantiated.

The JVM needs to distinctly know which value of


variable it needs to use. To avoid confusion to the
The interfaceName.variableName needs to be D JVM interfaceName.variableName is mandatory

No, Constructor, Static Initialization Block, Instance


B Initialization Block and variables cannot be abstract.

JUnit is a testing framework for unit testing. It


uses java as a programming platform. It is
Blackbox Testing A managed by junit.org community

@Test is used to annotate method under test,


@BeforeEach and @AfterEach are called
before and after each method respectively.
@BeforeClass and @AfterClass are called only
@AfterEach C once for each class.

assert method is used to compare actual and


expected results in Junit. It has various
implementation like assertEquals,
assertArrayEquals, assertFalse, assertNotNull,
 isEqual() A etc

@RunWith(PowerMockRunner.class) signifies
to use PowerMock JUnit runner. Along with
that @PrepareForTest(User.class) is used to
declare the class being tested.
mockStatic(Resource.class) is used to mock the
 @RunWith(PowerMockRunner.class) D static methods
Mockito.when(mockList.size()).thenReturn(100
); assertEquals(100, mockList.size()); is the
Mockito.if(..).then(..); C usage to implement if and then behavior

@InjectMocks annotation is used to inject


mock fields into the tested object
@Mock A automatically

<dependency>
<groupId>junits</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
JUnits can be used using dependency tag in
maven in pom.xml. The version as desired and
A available in repository can be used.

Serialization is not introduced with Java 8. It


Lambda Expression B was introduced with an earlier version of Java.

BooleanSupplier function interface represents


returns null if Boolean is passed as argum A supplier of Boolean-valued results.

Lambda expression enables us to pass


functionality as an argument to another
method, such as what action should be taken
Function D when someone clicks a button
Traversing through forEach method of Iterable
List.for() C with anonymous class
Sequential stream and parallel stream are two
random and synchronized A types of stream provided by java.

SessionManagement is not a core interface of


Hibernate. Configuration, Criteria,
SessionFactory, Session, Query and Transaction
Session C are the core interfaces of Hibernate

SessionFactory is a thread-safe object. Multiple


A threads can access it simultaneously

load() method returns proxy object. load()


method should be used if it is sure that
get() C instance exists

 get() method hits database always. Also, get()


get() D method does not return proxy object.
update() method can only be used inside
session. update() should be used if session
kill() B does not contain persistent object.

Attached() is not a state of object in Hibernate.


Detached(), Persistent() and Transient() are the
Transient() A only states in Hibernate
Database table configuration is stored in .hbm
.sql B file
Source
https://www.sanfoundry.com
Questions Option A
What will be the output of the following Java program?
class array_output {
public static void main(String args[]) iiiii
{
char array_variable [] = new char[10];
What for will
(intbe
i = the
0; i output of the
< 10; ++i) { following Java program?
class mainclass {
array_variable[i] = 'i';
publicSystem.out.print(array_variable[i]
static void main(String args[]) + "" ); 66
{ i++;
char
} a = 'A';
} a++;
}System.out.print((int)a);
What}will be the output of the following Java program?
class
} mainclass {
public static void main(String args[])
{
boolean var1 = true;
boolean var2 = false;
if (var1) 0
System.out.println(var1);
else
System.out.println(var2);
}
}

What will be the output of the following Java code?


class booloperators {
public static void main(String args[])
{ 0
boolean var1 = true;
boolean var2 = false;
System.out.println((var1 & var2));
}
}

What will be the output of the following Java code?


class asciicodes {
public static void main(String args[])
{ 162
char var1 = 'A';
char var2 = 'a';
System.out.println((int)var1 + " " + (int)var2);
}
}
result = func (n - 1);
return result;
}
}
class Output
{
public static void main(String args[])
{
recursion obj = new recursion() ; 1
System.out.print(obj.func(5));
}
}
What will be the output of the following Java code?

class Output
{ 257
public static void main(String args[])
{
What willInteger i = new
be the Integer(257);
output of the following Java program?
byte x = i.byteValue();
What will be the output
System.out.print(x); of the following Java program
final
class}class A
main_class
{ 22
}{ int i;
} public static void main(String args[])
class{ B extends A
{ int x = 9;
int j;if (x == 9)
System.out.println(j
{ + " " + i); Server
}
Which classint x = 8; system independent server side implementation?
provides
class inheritance
System.out.println(x);
{ }
public
} static void main(String args[]) 9
{
} B obj = new B();
obj.display();
}
}

What will be the output of the following Java program?


class box
{
 What intwill
width;
be the output of the following Java program?
classintbox
height;
{ int length; 12
}
intmainclass
class width;
{ int height;
int length;
public static void main(String args[])
}{
classboxmainclass
obj = new box();
{ obj.width = 10;
obj.height
public static=void
2; main(String args[])
{ obj.length = 10;
int
box obj1 = new* box();
y = obj.width obj.height * obj.length;
System.out.print(y);
} box obj2 = new box();
} obj1.height = 1;
obj1.length = 2;
obj1.width = 1;
obj2 = obj1;
System.out.println(obj2.height); 1
}
}
What will be the output of the following Java program?
class box
{
int width;
int height;
int length;
int volume;
void volume(int height, int length, int width)
{
volume = width*height*length;
} 0
}
class Prameterized_method
{
public static void main(String args[])
{
box obj = new box();
obj.height = 1;
obj.length = 5;
obj.width = 5;
obj.volume(3,2,1);
System.out.println(obj.volume);
}
}

What will be the output of the following Java program?


class equality
{
int x;
int y;
boolean isequal()
{
return(x == y);
}
} 0
class Output
{
public static void main(String args[])
{
equality obj = new equality();
obj.x = 5;
obj.y = 5;
System.out.println(obj.isequal());
}
}
What will be the output of the following Java program?
class box
{
int width;
int height;
int length;
int volume;
void volume()
{
volume = width*height*length;
} 0
}
class Output
{
public static void main(String args[])
{
box obj = new box();
obj.height = 1;
obj.length = 5;
obj.width = 5;
obj.volume();
System.out.println(obj.volume);
}
}

In the following Java code, which call to sum() method is appropriate?


class Output
{

public static int sum(int ...x)


{
return;
}
static void main(String args[])
{
sum(10);
sum(10,20);
sum(10,20,30);
sum(10,20,30,40);
}
} only sum(1
What will be the output of the following Java program?
class area
{
int width;
int length;
int volume;
area()
{
width=5; 0
length=6;
}
void volume()
{
volume = width*length*height;
}
}
class cons_method
{
public static void main(String args[])
{
area obj = new area();
obj.volume();
System.out.println(obj.volume);
}
}
 What will be the output of the following Java code?
class box
{
int width;
int height;
int length;
int volume;
box()
{
width = 5;
height = 5;
length = 6; 100
}
void volume()
{
volume = width*height*length;
}
}
class constructor_output
{
public static void main(String args[])
{
box obj = new box();
obj.volume();
System.out.println(obj.volume);
}
}

What will be the output of the following Java code?


class San
{
San()throws IOException
{

}
class Foundry extends San
{
Foundry()
{

}
public static void main(String[]args)
{

}
} compile ti
What will be the output of the following Java code?
class box
{
int width;
int height;
int length;
int volume;
void finalize()
{
volume = width*height*length;
System.out.println(volume);
}
protected void volume() 150
{
volume = width*height*length;
System.out.println(volume);
}
}
class Output
{
public static void main(String args[])
{
box obj = new box();
obj.width=5;
obj.height=5;
obj.length=6;
obj.volume();
}
}
What will be the output of the following Java code?
class area
{
int width;
int length;
int area;
void area(int width, int length)
{
this.width = width;
this.length = length; 00
}

}
class Output
{
public static void main(String args[])
{
area obj = new area();
obj.area(5 , 6);
System.out.println(obj.length + " " + obj.width);
}
}

What will be the output of the following Java code?


class San
{
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)


{
San s=new San();
s.m1(20,20);
}
} int float m
What will be the output of the following Java code?
class overload
{
int x;
int y;
void add(int a)
{
x = a + 1;
}
void add(int a, int b)
{ 5
x = a + 2;
}
}
class Overload_methods
{
public static void main(String args[])
{
overload obj = new overload();
int a = 0;
obj.add(6);
System.out.println(obj.x);
}
}
What will be the output of the following Java code?
class overload
{
int x;
int y;
void add(int a)
{
x = a + 1; 6
}
void add(int a , int b)
{
x = a + 2;
}
}
class Overload_methods
{
public static void main(String args[])
{
overload obj = new overload();
int a = 0;
obj.add(6, 7);
System.out.println(obj.x);
}
}
What will be the output of the following Java code?
class overload
{
int x;
double y;
void add(int a , int b)
{
x = a + b;
}
void add(double c , double d)
{
y = c + d;
}
overload()
{
this.x = 0; 6.6
this.y = 0;
}
}
class Overload_methods
{
public static void main(String args[])
{
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);
}
}
 What will be the output of the following Java code?
class test
{
int a;
int b;
void meth(int i , int j)
{
i *= 2;
j /= 2;
} 10 20
}
class Output
{
public static void main(String args[])
{
test obj = new test();
int a = 10;
int b = 20;
obj.meth(a , b);
System.out.println(a + " " + b);
}
}

What will be the output of the following Java code?


class test
{
int a;
int b;
test(int i, int j)
{
a = i;
b = j;
}
void meth(test o) 10 20
{
o.a *= 2;
O.b /= 2;
}
}
class Output
{
public static void main(String args[])
{
test obj = new test(10 , 20);
obj.meth(obj);
System.out.println(obj.a + " " + obj.b);
}
}
What will be the output of the following Java code?
class access
{
public int x;
private int y;
void cal(int a, int b)
{
x = a + 1;
y = b;
} 33
}
public class access_specifier
{
public static void main(String args[])
{
access obj = new access();
obj.cal(2, 3);
System.out.println(obj.x + " " + obj.y);
}
}

 What will be the output of the following Java code?


class access
{
public int x;
private int y;
void cal(int a, int b)
{
x = a + 1;
y = b;
}
void print() 23
{
System.out.println(" " + y);
}
}
public class access_specifier
{
public static void main(String args[])
{
access obj = new access();
obj.cal(2, 3);
System.out.println(obj.x);
obj.print();
}
}
What will be the output of the following Java code?
class static_out
{
static int x;
static int y;
void add(int a, int b)
{
x = a + b;
y = x + b;
}
}
public class static_use 7 7.4
{
public static void main(String args[])
{
static_out obj1 = new static_out();
static_out obj2 = new static_out();
int a = 2;
obj1.add(a, a + 1);
obj2.add(5, a);
System.out.println(obj1.x + " " + obj2.y);
}
}
What will be the output of the following Java program?
class access
{
public int x;
static int y;
void cal(int a, int b)
{
x += a ;
y += b;
}
} 12
class static_specifier
{
public static void main(String args[])
{
access obj1 = new access();
access obj2 = new access();
obj1.x = 0;
obj1.y = 0;
obj1.cal(1, 2);
obj2.x = 0;
obj2.cal(2, 3);
System.out.println(obj1.x + " " + obj2.y);
}
}

What will be the output of the following Java program?


class access
{
static int x;
void increment()
{
x++;
}
}
class static_use
{ 12
public static void main(String args[])
{
access obj1 = new access();
access obj2 = new access();
obj1.x = 0;
obj1.increment();
obj2.increment();
System.out.println(obj1.x + " " + obj2.x);
}
}
What will be the output of the following Java program?
class static_out
{
static int x;
static int y;
void add(int a , int b)
{
x = a + b;
y = x + b;
}
}
class static_use
{
public static void main(String args[])
{
static_out obj1 = new static_out();
static_out obj2 = new static_out();
int a = 2;
obj1.add(a, a + 1);
obj2.add(5, a);
System.out.println(obj1.x + " " + obj2.y);
}
} 77

What will be the output of the following Java program?


class Output
{
public static void main(String args[])
{
int arr[] = {1, 2, 3, 4, 5};
for ( int i = 0; i < arr.length - 2; ++i)
System.out.println(arr[i] + " ");
}
} 12

What will be the output of the following Java program?


class Output
{
public static void main(String args[])
{
int a1[] = new int[10];
int a2[] = {1, 2, 3, 4, 5};
System.out.println(a1.length + " " + a2.length);
}
} 10 5
What will be the output of the following Java program?
class string_demo
{
public static void main(String args[]) I
{
String obj = "I" + "like" + "Java";
System.out.println(obj);
}
}

What will be the output of the following Java program?


class string_class
{
public static void main(String args[]) I
{
String obj = "I LIKE JAVA";
System.out.println(obj.charAt(3));
}
}

What will be the output of the following Java program?


class string_class
{
public static void main(String args[])
{ 9
String obj = "I LIKE JAVA";
System.out.println(obj.length());
}
}

What will be the output of the following Java program?


class string_class
{
public static void main(String args[])
{
String obj = "hello";
String obj1 = "world";
String obj2 = obj;
obj2 = " world";
System.out.println(obj + " " + obj2);
}
} hello hello
What will be the output of the following Java program?
class string_class
{
public static void main(String args[])
{
String obj = "hello";
String obj1 = "world";
String obj2 = "hello";
System.out.println(obj.equals(obj1) + " " + obj.equals(obj2));
}
} false false

What will be the output of the following Java program?


class box
{
int width;
int height;
int length;
int volume;
void volume(int height, int length, int width) 0
{
volume = width * height * length;
}
}
class Prameterized_method{
public static void main(String args[])
{
box obj = new box();
obj.height = 1;
obj.length = 5;
obj.width = 5;
obj.volume(3, 2, 1);
System.out.println(obj.volume);
}
}
What will be the output of the following Java program?
class equality
{
int x;
int y;
boolean isequal()
{
return(x == y);
} 0
}
class Output
{
public static void main(String args[])
{
equality obj = new equality();
obj.x = 5;
obj.y = 5;
System.out.println(obj.isequal);
}
}
What will be the output of the following Java program?

class box
{
int width;
int height;
int length;
int volume;
void volume()
{
volume = width * height * length; 0
}
void volume(int x)
{
volume = x;
}
}
class Output
{
public static void main(String args[])
{
box obj = new box();
obj.height = 1;
obj.length = 5;
obj.width = 5;
obj.volume(5);
System.out.println(obj.volume);
}
}

What will be the output of the following Java program?

class Output
{
static void main(String args[]) 1
{
int x , y = 1;
x = 10;
if(x != 10 && x / 0 == 0)
System.out.println(y);
else
System.out.println(++y);
}
}
What will be the output of the following Java program?

class area
{
int width;
int length;
int height;
area()
{ 0
width = 5;
length = 6;
height = 1;
}
void volume()
{
volume = width * height * length;
}
}
class cons_method
{
public static void main(String args[])
{
area obj = new area();
obj.volume();
System.out.println(obj.volume);
}
}

What will be the output of the following Java snippet, if attempted to compile and run this code
with command line argument “java abc Rakesh Sharma”?
public class abc
{
int a=2000;
public static void main(String argv[])
{
System.out.println(argv[1]+" :-Please pay Rs."+a);
}
}  Compile time error
What will be the output of the following Java program?
final class A
{
int i;
}
class B extends A 22
What { will be the output of the following Java program?
classintAj;
{ System.out.println(j + " " + i);
} int i;
class inheritance
public void display()
{ {
public static void main(String args[])
System.out.println(i);
{}
B obj = new B();
} obj.display();
class
} B extends A
{}
int j;
public void display()
{
What willSystem.out.println(j);
be the output of the following Java program?
class Abc }
{}
publicDynamic_dispatch
class static void main(String[]args)
{ {
String[] elements = { "for", "tea", "too" };
public static
String first void main(String> args[])
= (elements.length 0) ? elements[0]: null;
} {
} B obj2 = new B(); Compilatio
obj2.i = 1;
obj2.j = 2;
A r;
r = obj2; 1
r.display();
}
}
What will be the output of the following Java code?
class exception_handling
{
public static void main(String args[])
{
try
{
int a = args.length; 0
int b = 10 / a;
System.out.print(a);
}
catch (ArithmeticException e)
{
System.out.println("1");
}
}
}

What will be the output of the following Java code?

class exception_handling
{
public static void main(String args[])
{ A
try
{
throw new NullPointerException ("Hello");
}
catch(ArithmeticException e)
{
System.out.print("B");
}
}
}
What will be the output of the following Java code?

class exception_handling
{
public static void main(String args[])
{
try
{
int a = 1;
int b = 10 / a;
try
{
if (a == 1) A
a = a / a - a;
if (a == 2)
{
int c[] = {1};
c[8] = 9;
}
}
finally
{
System.out.print("A");
}
}
catch (Exception e)
{
System.out.println("B");
}
}
}
What will be the output of the following Java code?

class exception_handling
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 10 / a;
System.out.print(a);
try
{
if (a == 1)
a = a / a - a;
if (a == 2)
{
int []c = {1};
c[8] = 9;
}
}
catch (ArrayIndexOutOfBoundException e)
{
System.out.println("TypeA");
}
catch (ArithmeticException e)
{
System.out.println("TypeB");
}
}
} TypeA
Option B Option C Option D Answer Explanation

ijklm None of the


 0 1 2 3 4 A
mentioned

67 65 64 A

1 1 0 C

1 1 0 D

65 97 67 95 66 98 B
None of the
120 0 A
mentioned

i.byteValue() method returns the value of wrapper i as


a byte value. i is 257, range of byte is 256 therefore i
value exceeds byte range by 1 hence 1 is returned and
256 1 0 C stored in x.

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
Runtime Compilation
33 D
Error Error

ServerSocket is a java.net class which provides system


ServerRea independent
Two variablesimplementation of server
with the same name can’tside socket in
be created
Socket ServerSocket D
der aconnection.
class.

OutPut: $ javac main_class.java


Exception in thread "main" java.lang.Error: Unresolved
8 CompilationErrorRuntimeError C
compilation problem:
Duplicate local variable x

200 400 100 B

When we assign an object to another object of same


type, all the elements of right side object gets copied
to object on left side of equal to, =, operator.
2 Runtime ErrorGarbage Value A
1 6 25 C

1 0 1
1 25 26 C

only sum(1only sum(10) & sum(10,20D sum is a variable argument method and hence it can take any numb
1 30 Error D

Variable height is not defined.


150 200 250 B

run time ercompile and unreported exc If parent class constructor throws any checked exception, compulsor
200 Runtime Error
Compilation Error A
56 65 55 C

this keyword can be used inside any method to refer to the current o

float int m compile timerun time error While resolving overloaded method, compiler automatically promotes
6 7 8 C
7 8 9 C
6.4 6.4 6.4 6 4 6.4 D

For obj.add(a,a); ,the function in line number 4 gets executed and va


20 10 20 40 40 20 A

 Variables a & b are passed by value, copy of their values are made

20 10 20 40 40 20 B

Class objects are always passed by reference, therefore changes do


Exception in thread "main" java.lang.Error:
23 Runtime Error
Compilation Error C Unresolved compilation problem:
The field access.y is not visible

33 Runtime Error
Compilation Error B
6 6.4 79 97 C
23 32 15 D

11 22 Compilation Error C

All objects of class share same static variable, all the objects share s
C

66 79 97

123 1234 12345 arr.length() is 5, so the loop is executed for three times

5 10 0 10 05 Arrays in java are implemented as objects, they contain an attribute


Like Java I Like Java D

Java defines an operator +, it is used to concatenate strings.

L K E A

 charAt() is a method of class String which gives the character specif

10 11 12 C

world worl hello world world hello


D

true true true false false true equals() is method of class String, it is used to check equality of two

1 6 25 C
1 0 1 B
5 25 26 B

2 Runtime Error
Compilation Error D

main() method must be made public. Without main() being public jav
1 25 30 D

CompilatioCompilation Compilation a Main method is static and cannot access non static variable a.
33 Runtime Error
Compilation Error D

class A has been declared final hence it cannot be inherited by any o

An exceptio
The variable The
f variable fi The value at the 0th position will be assigned to the variable first.

2 3 4 B

 r is reference of type A, the program assigns a reference of object o


1 Compilation Error
RuntimeError B

B Compilation ErorRuntimeError D

Try block is throwing NullPointerException but the catch block is use


B AB BA A

The inner try block does not have a catch which can tackle ArrayInde
C

TypeB Compilation Runtime Error try without catch or finally


hence it can take any number as an argument.
ecked exception, compulsory child class constructor should throw the same checked exception as its parent, otherwise code w
hod to refer to the current object. this is always a reference to the object on which the method was invoked.

piler automatically promotes if exact match is not found. But in this case, which one to promote is an ambiguity.
mber 4 gets executed and value of x is 4. For the next function call, the function in line number 7 gets executed and value of y is
py of their values are made on formal parameters of function meth() that is i & j. Therefore changes done on i & j are not reflect

rence, therefore changes done are reflected back on original arguments. obj.meth(obj) sends object obj as parameter whose va
iable, all the objects share same copy of static members, obj1.x and obj2.x refer to same element of class which has been incr
or three times

s, they contain an attribute that is length which contains the number of elements that can be stored in the array. Hence a1.leng
concatenate strings.

h gives the character specified by the index. obj.charAt(3) gives 4th character i:e I
sed to check equality of two String objects, if they are equal, true is retuned else false.
hout main() being public java run time system will not be able to access main() and will not be able to execute the code.
non static variable a.
cannot be inherited by any other class. Hence class B does not have member i, giving compilation error.

gned to the variable first.

signs a reference of object obj2 to r and uses that reference to call function display() of class B.
n but the catch block is used to counter Arithmetic Exception. Hence NullPointerException occurs since no catch is there which
h which can tackle ArrayIndexOutOfBoundException hence finally is executed which prints ‘A’ the outer try block does have cat
s parent, otherwise code won’t compile.
n ambiguity.
s executed and value of y is 6.4
done on i & j are not reflected back on original arguments. a & b remain 10 & 20 respectively.

obj as parameter whose variables a & b are multiplied and divided by 2 respectively by meth() function of class test. a & b bec
f class which has been incremented twice and its value is 2.
in the array. Hence a1.length gives 10 and a2.length gives 5.
to execute the code.
ince no catch is there which can handle it, runtime error occurs.
uter try block does have catch for ArrayIndexOutOfBoundException exception but no such exception occurs in it hence its catch
tion of class test. a & b becomes 20 & 10 respectively.
n occurs in it hence its catch is never executed and only ‘A’ is printed.

You might also like