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

Java

The document provides answers to 20 questions related to Java programming concepts. Some key points covered include: 1. Exception handling in Java and how exceptions are thrown and caught. 2. Differences between primitive types and object references in Java and how == operator works. 3. Features of interfaces in Java like default and static methods. 4. Purpose and advantages of exception handling in Java programs. 5. Concepts like inheritance, overriding, polymorphism and how they work in Java. 6. Usage of finally block and exception propagation in try-catch blocks. 7. Lambda expressions and functional interfaces in Java. 8. Collections classes like HashSet and differences between equals()

Uploaded by

Praveen 1605
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
352 views

Java

The document provides answers to 20 questions related to Java programming concepts. Some key points covered include: 1. Exception handling in Java and how exceptions are thrown and caught. 2. Differences between primitive types and object references in Java and how == operator works. 3. Features of interfaces in Java like default and static methods. 4. Purpose and advantages of exception handling in Java programs. 5. Concepts like inheritance, overriding, polymorphism and how they work in Java. 6. Usage of finally block and exception propagation in try-catch blocks. 7. Lambda expressions and functional interfaces in Java. 8. Collections classes like HashSet and differences between equals()

Uploaded by

Praveen 1605
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

Java:

1. What will be the output of the below code?


//Assume all the required import statements are added
Public class TestClass
@Test
Public void test(){
String a = “”;
AssertSame(“a”,a);

Ans: An exception is thrown at runtime as assertSame() is not a valid function


2. What will be the output of the below code?
Public class Demo{
Public static void main(String args[]){
Int i = 34;
Int j = 34;
System.out.println(i==j);
Integer i1 = new Integer(34);
Interger i2 = new Integer(34);
System.out.println(i1==i2);

Ans: true false

3. Which out of the following are true in regard to interfaces in Java?


(i) An interface can contain default and static method with defined bodies.
(ii) An object can be created of an interface
(iii) Multiple inheritance is allowed in Interfaces
(iv) Multi-level inheritance is not possible in interfaces

Ans: (i),(iii) & (iv)

4. Given
Public class Sample{
Public static void main(String[] args) throws Exception{
Try{
System.out.println(“In try block”);
System.exit(0);
}catch(Exception ex){
System.out.println(“In catch block”);
Ex.printStackTrace();
}finally{
System.out.println(“In finally block”);
}
}
}
Predict the output?
Ans: In try block
5. Which of the following are the advantages of exception handling in Java(Choose any 3 options)?
(i) To maintain the normal flow of execution
(ii) Meaningful error reporting
(iii) To document compile time error
(iv) To prevent the abrupt termination of a program

Ans: (i),(ii) &(iv)

6. Predict the output of the below code:


final class Square{
private double length,breadth;
public Square(double length,double breadth){
this.length = length;
this.breadth = breadth;
}
Square(Square square)
{
System.out.println("Copy constructor invoke");
length = square.length;
breadth = square.breadth;
}
public String toString(){
return "("+length+"+"+breadth+"i)";
}
}
class Main{
public static void main(String[] args){
Square square1 = new Square(110,115);
Square square2 = new Square(square1);
System.out.println(square2);
}
}
Ans: Copy constructor invoked
(110.0 + 115.0i)
7. Which of the following is a valid lambda expression?
Ans: (a,b) -> {int result; return result>0;}
8. What is the output of the following code?
Class Employee{
Void display(char c){
System.out.println(“Employee name starts with: “ +c+”.”);
System.out.println(“His experience is : 11 years.”);
}
}
Class Main extends Employee{
Void display(char c){
Super.display();
System.out.println(“Another employee name also starts with: “ +c+”.”);
New Employee().display(‘D’);
Display(7);
}
String display(int c){
System.out.println(“His experience is: “+c+” years.”);
Return “Bye”;
}
}
Public class Demo{
Public static void main(String a[]){
Employee emp = new Main();
Emp.display(‘S’);
}
}
Ans: Employee name starts with : S.
His experience is : 11 years.
Another employee name also starts with : S. Employee name starts with : D.
His Experience is : 11 years.
His Experience is : 7 years.
9. What is the output of the below code?
Import java.util.HashSet;
Public class TestDemo{
Public static void main(String…sss){
HashSet myMap = new HashSet();
String s1 = new String(“das”);
String s2 = new String(“das”);
NameBean s3 = new NameBean(“abcdef”);
NameBean s4 = new NameBean(:abcdef”);
myMap.add(s1);
myMap.add(s2);
myMap.add(s3);
myMap.add(s4);
System.out.println(myMap);
}
}
Class NameBean{
Private String str;
NameBean(String str){
This.str = str;
}
Public String toString(){
Return str;
}
}
Ans: [abcdef,das,abcdef]

10. Which among the following is/are true about Design Pattern
i. Design pattern depends upon abstraction
ii. Design patterns are completed designs that can be transformed directly into code
iii. Design pattern depends on abstraction, follows the process of Dependency Injection
iv. Design pattern is a template of solving problem that can be used in many real world
software development

Ans i & ii

11.From the below options identify the methods and constructors in Throwable that support chained
exceptions

i. Throwable.getCause()
ii. Throwable.initCause(Throwable)
iii. Throwable(String, Throwable)
iv. Throwable(Throwable)

Ans : Options i, iii & iv


12. What is Magic Number in Java in the context of java programming best practice
i. A number which gets printed on the console
ii. A direct usage of the number in the code
iii. A number which magically disappears from the code
iv. A number which is generated through error

Ans: Option2

A direct usage of the number in the code

13. Default format of LocalDate is


I. yyyy,mm,dd
II. yyyy.mm.dd
III. yyyy.dd.mm
IV. yyyy,dd,mm

Ans Option ii

14. Which among the following option are correct with respect to HashMap
I. Override boolean equals(Object o)
II. Override toString()
III. Override int hashCode()
IV. Override String hashCode()

Ans i, Override boolean equals(Object o)

15. Which of the foll interfaces are not a part of java collections framework(choose any2)
i. List
ii. Queue
iii. SoretdList
iv. ArrayList

Ans: Option iii & iv

16. Where are string objects stored in memory using “new” keyword?
i. In Stack Memory
ii. In String constant pool in Heap Memory
iii. In Native Methods stack Memory
iv. Anywhere in Heap Memory

Ans iv
17. What will be written at the line1 so that the below code will compile and run successfully?

Public class Main{


//line1
static {
X[0] = 102;
}
public static void main(String [] args){
System.out.println(x[0]);
}
}

Ans : option ii, static int[]x = new int[3];

18. Given
public class Employee{
private String roles;
Public Employee (String role) {this.role= role;}
Public Boolean equals (Employee emp){return emp.role.equqls(this.role)
}
}

Which among the following are correct with respect to the above code(Choose 2)

I. Code give compilation error due to private attribute emp.role cannot be accessed
II. Object.equals() method is not properly overriden
III. Code will compile successfully
IV. hasCode() method implementation is required

Ans iii & iv

19. Output of the below code

Public class TestDemo{


Public static void main(String [] args){
Integer n1 = new Integer (100);
Integer n2= new Integer (100);
Integer n3 =127;
Integer n4 =127;
System.out.println(n1==n2)
System.out.println(n3==n4)
}
}
Ans: false, true (option1)
20. Given

Public class ExceptionDemo{


Static class Car implements AutoCloseable{
Public void close(){
System.out.println(“Car dorr close”)
Throw new RuntimeException();
}
}

Public static vois main (String [] args){


Try{

//Line1

}catch (Exception e){

System.out.println(“catch exception”);
}finally{

System.out.println(“finally”)
}
}
}
I. Car car = new Car();
System.out.println(“try block”)

II. Car car = new Car();


Car.close();
System.out.println(“try block”)

III. Car car = new Car();

IV. System.out.println(“try block”)


Ans: all four

21. Given an abstract class Customer as below

Public abstract class Customer{


Public abstract String getCustomerType();
}

Select a valid implememntation of getCustomerType method in another class from the below
options

a. Abstract class C1 extends Customer{


Public abstract String getCustomerType(){ return “Premium”;}
}
b. Customer customer = new Customer(){
Public String getCustomerType(){ return “Premium”;}
}

c. class C1 extends Customer{


Public abstract String getCustomerType(){ return “Premium”;}
}

d. new Customer(){
return “Premium”;}

Ans: a & c

22. Given below

Public class Demo{


@BeforeClass
Public static void afterClass(){
System. Out.println(1)
}

@After
Public void before(){
System. Out.println(3)
}

@Test
Public void test(){
System. Out.println(5)
}

@Before
Public void fter(){
System. Out.println(4)
}
@AfterClass
Public static void afterClass(){
System. Out.println(2)
}
Ans Option 1 :

1
4
5
3
2
23. Which of the following is ‘FALSE’ regarding ‘super’ keyword in Java?

Option3, Super keyword can be used to call a parent class protected constructor which is
present in the same package

24. Which of the foll data structure is used by varargs in java

Ans: Option3, ArrayList

25. Which of the following is ‘FALSE’ regarding ‘this’ keyword in Java?

Ans option4, ‘this’ keyword can be used to create a block of code.

26. How many number of values can be accommodated by the varargs in java

Option4, Any number of values

27. Which of the foll statement is FALSE(Choose 2 options)


I. An interface can extend from only one interfaces
II. A class can extend from another class and at the same time implement any number of
interfaces
III. A class can extend multiple abstract classes
IV. Many classes can implement the same interface

Ans i and iii

28. Have a look at the foll code and choose the correct option

Class ReportUtil{
Int reportId =0;
Static {++reportId}
Static int employeeReportId;
Public void preReport(){
employeeReportId= reportId;
}
}
Ans: option 3 The code will not get compiled as instance variable cannot be reffered from the
static block

29. Which of the below methods can be defined in the single class in java. Select most
suitable(select 2 options)
1. Void add(int,int)
2. Void add(int,int, int)
3. int add(int,int)
I. 1 & 3 together
II. 1 & 2 together
III. 2 &3 together
IV. 1,2 &3 together
Ans Options ii and iii

30. Ria has a class called Account.java under two separate packages com.infy.debit and
com.infy.credit. Can she use the Account classof both the packages in another class called
ReportUtiljava of package com.infy.util

Option2: No, She cannot as there will be a compilation error stating that the import collides with
another import

31. Which of the following are true about enums in Java? (Choose 3 correct)
I. enums can implement any other interface in java
II. an instance of enum can be created outside of enum itself
III. enum cant extend any other class except the abstract base class java.lang.enum
IV. enum can be used to implement singleton design pattern

Ans i, iii & iv

32. What’s is true with respect to abstract class being given below

Abstract class Employee{


//fields and constructor
Public void salaryComputer()
{
// code goes here
}
Public abstract void taxReduce()
{
// code goes here
}
Public abstract void benifitsInclude();
}

Ans: option4. Abstract method of class Employee has definition

33. Which of the following are NOT good practice for creating objects.
a. Lazy initialization of objects
b. Creating String literals instead of String objects
c. Creating Wrapper objects instead of primitives
d. invoking static factory methods for immutable classes
Ans option c

34. Which among the foll are valid lamda expressions to sort the numbers in numberlistin
descending order choose 3
a. numberList.sort((x,y)->x.compareTo(y))
b. numberList.sort(int x,int y)->x.compareTo(y))
c. numberList.sort((x,y)->{return x.compareTo(y))}
d. numberList.sort((Integerx,Integer y)->x.compareTo(y))

Ans
35. What is the output for the below code

public class VarArgsDemo{

static void func(int...x)


{
System.out.println("Number of arguments "+x.length);

for(int i:x)
System.out.print(i+"");
System.out.println();
}
void func(int a) //Line1
{ System.out.println("one"); }

public static void main(String[]args){


new VarArgsDemo().func(150);
func(11, 12, 13, 14);
func(); }
}

Ans:Option B

Number of arguments1
150
Number of arguments4
11121314
Number of arguments0

36.Given, Assume all the required imports are added

Public class TestDemo{


Private AaaryList list //Line1
@Test //lin2
Public void test(){
assertTrue(list.isEmpty());
}
}
Which of the following is true regarding the above code fragment

Ans : if we replace Line2 by “@Test(expected = NullPointerException.class)” the test


case will pass

37. Given
HashMap <Integer, Integer> myMap = new HashMap<Integer, Integer>();
myMap.put(1001,5);
myMap.put(1002,8);
myMap.put(1002,5);
myMap.replace(1002,5, 100);
system.out.println(myMap)

Ans: {1001=5, 1002=100}


38. What is the result when the foll code is compiled?
Class Student extends Exception{}
Class Hosteller extends Student{}
Public class StudentTester{
Public static void main (String args[]){
Try{
//some monitored code
Throw new Hosteller();

}Catch(Student st){
System .out.println(“Student class Exception”);
}catch (Hosteller host){
System .out.println(“Hosteller class Exception”);
}
}
}

Ans: The code will not compile Unreachable catch for Hosteller because Student
class exception is caught before Hosteller

39.
class Operations{
Public void addition(){}
}

Class AdvOperations extends Operations{


Void addition()//line1

{}
}
Line 1 generates compilation error . which of then below option helps to resolve this

Ans: public keyword has to be added

40. What will be in line1 to get the output as 150. Choose 2

class EmployeeUtil {
//line1
double amountTax;
public double taxCalculator(double salary)
{
amountTax = salary *TAX_PERCENTAGE/100;
return amountTax;
}
}
public class ConstantMain
{
public static void main(String[] args) {
System.out.println(new EmployeeUtil().taxCalculator(5000));
}
}

Ans:

final int TAX_PERCENTAGE=3;

static int TAX_PERCENTAGE=3;

41.

interface Component {
String cname = "Motor";
String getName(String name);
}

public class Demo implements Component{


public String getName(String name) {
System.out.println("Inside Demo Class");
return "Componenet from interface is :" + cname+"and component
from class is "+ name+ ";";
}

public static void main(String[] args) {

Demo demo = new Demo();


System.out.println(demo.getName("Battery"));
demo.getName("Battery");

}
}

Ans Inside Demo Class


Componenet from interface is :Motorand component from class is Battery;
Inside Demo Class

42.

public class CollectionTest {

public static void main(String[] args) {

Collection<Integer> employeeCollection = new HashSet();


collection.add(1001);
collection.add(1002);
collection.add(1001);

Set<Integer> newSet = new TreeSet();


newSet.addAll(employeeCollection);
System.out.println(newSet);

}
}

Ans : Runtime Exception : null pointer Exception

43. Which of the following regarding an abstract class is/are true in Java

i)Object of an abstract class cant be created

ii) An abstract class is designedonly to act as a base class in hierarchy to br


inherited by other classes

Ans : Both i & ii

44.
public class CodeForException {
//public static void main(String[] args) {
public void callMe() throws Exception{
try
{
int value=3/0;
}
catch (ArithmeticException aa)
{

System.out.println(aa);
}
}
public void calling()
{

callMe();
}
}

Ans : Compilation error

45.

public class Demo {


private static String id;
private Random random = new Random();

public Demo(){

if(id ==null){ {
}
id = "ACC1101"+ Math.abs(random.nextInt());
}
}

public String getid() {


return id;

}
}

Ans - if(id==null){

46. Given
//Assume all the required imports are added

public class TestDemo {


private ArrayList list;//Line1
@Test //Line2 (expected = NullPointerException.class)
public void test(){
assertTrue(list.isEmpty());
}

Which of the following statement is true regarding the above code fragment?

Ans : if we replace Line2 by “@Test(expected = NullPointerException.class)” the


test case will pass

47.
public static void main(String args[])
{
HashMap<Integer, Integer> myMap = new HashMap<Integer, Integer>();
myMap.put(1001, 5);
myMap.put(1002, 8);
myMap.put(1002, 5);
myMap.replace(1002,5,100);
System.out.println(myMap);
}

Ans: {1001=5, 1002=100}

48. what is the result when the following code snippet is compiled?
class Student extends Exception{}
class Hosteller extends Student{}
public class StudentTester {
public static void main(String[] args){
try{
//some monitored code
throw new Hosteller();
}
catch (Student st){
System.out.println("Student class exception");
}
catch (Hosteller host){
System.out.println("Hosteller class exception");
}
}

Ans: The code will not compile Unreachable catch for Hosteller because Student
class exception is caught before Hosteller

49.

class Operations
{
public void addition()
{}
}
class AdvOperations extends Operations {
void addition()//Line1
{}

Line 1 generates Compilation error. Which of the below options helps to resolve
this?

Ans: public keyword has to be added

50.

Public class TestDemo{

Public void main(int x){

System.out.println(“Main1”)

Public static void main(String args[]){

System.out.println(“Hello Main”)

 }

Ans : option 4 : Hello Main


51.
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;
public class ABC {
public static void main(String args[])
{
TreeSet set = new TreeSet();
set.add("a");
set.add(6);
set.add("c");
Iterator ite =(Iterator) set.iterator();
while(ite.hasNext()){
System.out.println(ite.next()+"");

}
}

Ans: The code will give java.lang.ClassCastException: java.lang.String incompatible


with java.lang.Integer

52. what is the output of the following code?

public class Demo5 {


public static void main(String[] args){

int x[][] = new int [4][]; //Line 1


x[0] = new int [1];
x[1] = new int [2];
x[2] = new int [3];
x[3] = new int [4];
int a,b,c=0;
for(a=0; a<4; a++){
for(b=0; b<a+1; b++){
x[a][b] = c;
c++;
}
}
for(a=0; a<4; a++){
for(b=0; b<a+1; b++){
System.out.print("" + x[a][b]);
c++;
}
System.out.println();

}
}
}
Ans:

0
12
345
6789

53. which of the following keyword is used to prevent the content of a variable from
being modified from outside.

Ans - Final

54.

class Book{
int bookid =2356;

}
class Book1 extends Book{
int bookid = 1167;
}
class Book2 extends Book1{
int bookid = 2378;//Line8
void display(){
System.out.println(super.super.bookid);//Line10
System.out.println(super.bookid);//Line11
System.out.println(bookid);
}
}
public class Demo2 {
public static void main(String[] args){
Book2 book2 = new Book2();
book2.display();
}
}

Ans – Compilation fails, because of an error in Line10 as super keyword is


unexpected.

55. Consider the below class and identify the extension of the output file when we
execute the command javac Employee.java

class Employee1 {
private int x=10;
public void showX(){
System.out.println(x);
}
}

Ans - .java

56. which of the below if statement is used to find a year is a leap year or not
Ans: if((y%4==0) && (y%100 !=0) || (y%400==0))

57. Analyze the below code and predict the output when executed the code

public class Demo6 extends Book{


int bookid = 4362;
public int getvarchar(){
return bookid;
}
public void Cell(){
System.out.println(getvarchar());//Line1
}
public static void main(String[] args){
Book book = new Book();
super.Cell();//Line 2
}
}
class Book{
int bookid = 17252;
public int getvarchar(){
return bookid;

}
}

Ans: Compilation error in line 2 as super keyword cannot be used in static context

58. have a look at the following class and predict what should be placed at line 1 to
get 150.0 as output when the code gets executed? (choose 2 options)

class EmployeeUtil{
//line1
double amountTax;
public double taxCalulate(double salary){
amountTax = salary*TAX_PERCENTAGE/100;
return amountTax;

}
}
public class ConstantMain{
public static void main(String[] args){
System.out.println(new EmployeeUtil().taxCalulate(5000));

}
}

Ans:

static int TAX_PERCENTAGE=3;

final int TAX_PERCENTAGE=3;


59. if the child class of an abstract class does not implement all its abstract methods then it should
be declared as

Ans: Option A: Abstract class

 60. Which of the following statements regarding an abstract class is/are true in Java

I. Object of an abstract class cant be created


II. An abstract class is designed only to act as a base class in hierarchy to be inherited by other
classes

 Ans : Both I & II

61. which of the following is valid function used to read values using Scanner in java (choose 3)

1. nextInt()
2. nextChar()
3. nextLong()
4. nextLine()

Ans: option 1,3 and 4

62. What will be output of the below code snippet?

package Example;

public class Pet {


public void displayName(){
System.out.println("Inside Pet");
}

package java.pac;
import Example.Pet;
public class Dog extends Pet{
@Override
public void displayName(){
System.out.println("Inside Dog");
}

 package com.infy;
import Example.Pet;
public class Demo7 {
public static void main(String[] args){
Pet pet = new Dog();//Line1
pet.displayName();
}

Ans – Compilation error at Line1 due to ClassCastException

63. Which of the foll is FLASE regarding polymorphism in JAVA

a. Polymorphism is the ability of an object to take different forms


b. Polymorphism can be as a single action that can be performed in different ways
c. Polymorphism means different forms by creating different classes that are reffered to each
other by inheritance
d. Polymorphism is using same method multiple times in a class with different parameters

Ans Option D

64. what is the result of the following code?


public class Vehicle {
static class Car{
public void go(){
System.out.println("Car Ignition");
}
}
static class ElectricCar extends Car{
public void go(){
System.out.println("ElectricCar Ignition");
}
}
static class PetrolCar extends Car{
public void go(){
System.out.println("PetrolCar Ignition");
}
}
public static void main(String[] args){
Car car = new ElectricCar();
car.go();
}
}
Ans- ElectricCar Ignition
65. If child class of abstract class doesnot implement all its abstract methods then
it should be declared as?

Ans – abstract class

66. which are valid upper bound by class Employee of list. (Doubt)

Ans - List<?extends Employee>

Choose any 2

public class App {


       public static void main(String[] args) {
              String msg = null;
              try {
                     System.out.println(msg.length());
                    
              }catch(NullPointerException ex) {
                     System.out.println("Exception is caught here");
                    
                     throw ex; //Line 1
                     System.out.println(msg); //Line 2
              }
       }
}

Ans:

//a, b

A.Place line2 before line 1

B.Remove line 2 ie after throw, there should not be any statements

interface Book {
       static void bookNmae() {
              System.out.println("in interface book");
       }
}

public class BookImpl implements Book{


       void bookName() {
              System.out.println("In BookImpl Class");
       }
}

public class BookApp {

       public static void main(String[] args) {


              // TODO Auto-generated method stub
              new BookImpl().bookName();
       }

ANS: code compiles  and prints “In BookImpl Class”

Which of the below is not a valid classification of design pattern

Creational Pattern

Structural pattern

Behavioral Pattern

Java pattern

ANS: D Java pattern

Section 1:

1. What is the output of the following code?


public class Main{
public static void main(String args[]){
int twoD[][] = new int [4][]; //Line 1
twoD[0] = new int [1];
twoD[1] = new int [2];
twoD[2] = new int [3];
twoD[3] = new int [4];
for (int i=0;i<4;i++){
for (int j=0;j<i+1;j++){
twoD[i][j]; //Line 2
}
System.out.println("executed");

}
}

Ans – Compilation error in Line 2 as there is no Assignment operator used

2. Which of the following statement is false about an object in java?

Ans – Object can communicate with each other

3. What is the output of the code given below?


public class ABC {
public static void main(String args[])
{
boolean flag = false;
if(flag = true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
Ans- true
4. Ria has a class called ‘Account.java’ under two separate packages. Com.infy.debit and
com.infy.credit can see give the account.java of both the packages in another class called
‘ReportUtil.java’ of package com.infy.util?

Ans – No She cannot as there will be compilation error stating the import collides with another import.

5. Identify the suitable datatype to be used for variable ‘b’ at line 1?


class Expression {
public void calc()
{
double x=10;
int y = 20;
float z= 30;
//Line 1 --- Answer is double
b=x+y+z;

Ans – double

6. What is the result when the following code is compiled and executed?

class Demo {
int x=1;
int y=2;
Demo display(Demo demoParam){
Demo obj = new Demo();
obj = demoParam;
obj.x = demoParam.x++ + ++ demoParam.y ;
demoParam.y = demoParam.y;
return obj;
}
public static void main(String[] args){
Demo obj1 = new Demo();
Demo obj2 = obj1.display(obj1);
System.out.println("obj1.x = " + obj1.x + "obj1.y = " + obj1.y);
System.out.println("obj2.x = "+ obj2.x + "obj1.y = " + obj2.y);

}
}

Ans:
obj1.x = 4obj1.y = 3
obj2.x = 4obj1.y = 3

7. Have a look at the following class and predict the option that is correct?
public class CodeForException {
public void callMe() throws Exception{
try{
int value = 3/0;

}catch (ArithmeticException ae){


System.out.println(ae);
}
}
public void calling(){
callMe();
}

Ans: The code will face issues during compilation as the calling code neither handles nor throws
Exception

8. What will be output of the code when executed?

public class OperatorTester {


public static void main(String[] args){
int a = 10;
int b = 15;
if (++a <(b=b-=4)||(a=a+=4)>b++){
System.out.println(a+"," +b);
}
}
}

Ans – 15,12

9. What is the result when the following code snippet is executed?


class Employee {
static String name = " ";
public static void main(String[] args) throws Exception{
try{
name+="jo";
throw new Exception();

}catch(Exception e){
name+="hn";

}finally{
name+="s";
empName();
name+="on";
}
System.out.println(name);
}
static void empName(){
throw new NullPointerException();
}
}

Ans – The code will give java.lang.NullPointerException in finally block when executing

10. What is the result when the code is compiled and executed?

class Calculator {
int a = 123, b=200;
public void display(){
System.out.println("a:" + a + "b:" + b+"");
}
}
class CalculatorDemo{
public static void main(String[] args)
{
Calculator calculator1 = new Calculator();//Line1
Calculator calculator2 = calculator1; //Line2
calculator1.a+= 1;
calculator1.b+= 1;
System.out.println("calculator1 values:");
calculator1.display();
System.out.println("calculator2 values:");
calculator1.display();
}
}

Ans –
calculator1 values:
a:124b:201
calculator2 values:
a:124b:201

Section2
1. What can be expected when the following code is compiled
abstract class Customer {

public int custId;//Line1


Customer()//Line2
{
custId=23456;//Line3
}
abstract public void setId();
abstract final public void getid();//Line4
}

Ans : Option D: Compilation error in Line 4 abstract methods cant be final

2. What is the correct way of placing ‘this’ keyword in a constructor?


Ans Option A : First Statement

3. At what position should Varargs be placed in a parameterised method


Ans Option B: Last Place

4.Predict the output of the following code

public class Demo {


static int x=232;
int y=135;
public void display(){
System.out.print("Inside Demo");}
public static void show(){
System.out.print(x);
}

public static void main(String[]args)


{
Demo.show();//Line 1
Demo demo=new Demo();
demo.show(); //Line2
show();//Line3
demo.display();
}
}

Ans: Option A: Compilation error in line2 as static method cannot be called with
object reference

5. Which of the following keyword can be used to restrict a class to be implemented


in java

Ans Option B. Final

6. Given below. What will be the output when code is compiled and executed
public class Parent {

public final void show(){


System.out.println("show() inside Employee");
}
}

final class Child extends Parent {


public void show1() { //Line1
final int x=100;
System.out.println("show() inside Unit");
System.out.println(x);
}}
public class Demo {

public static void main(String[] args) {


Parent parent = new Child();
new Child().show1();//Line2

}}

Ans: Option D

show() inside Unit

100

7. Which of the following is FALSE regarding parameterized constructor in Java

a. parameterised constructor should have void as return type


b. parameterised constructor can take any number of parameters
c. parameterised constructor cannot have private access modifier
d. parameterised constructor throw an exception

Ans Option c parameterised constructor cannot have private access modifier

8. What is the output of the following

public class Trainer{

public void display(String name) {


System.out.println("I am a trainer");
print(name);
}

public void print(String name) {


System.out.println(" I train "+ name+ ".");
}
}
public class Trainee extends Trainer {
String myname;

public Trainee(String myname) {


super();
this.myname= myname;
}

public void display(String name) {


super.display(name);
System.out.println("I am a trainee");
print("Java");
}

public void print(String name) {


super.print(name);
System.out.println("I want to learn " +name+"");
}

public static void main(String[] args) {


Trainer trainee = new Trainee("XYZ");
trainee.display("Java");

}}

Ans: Option B

I am a trainer
I train Java.
I want to learn Java
I am a trainee
I train Java.
I want to learn Java

9. Which of the following is FALSE regarding ‘this’ keyword in java?

Ans--- optionD, ‘this’ keyword can be used to create a block of code.

10. Given

Class Parent{}
Class Child extends Parent{}
Final class GrandChild extends Child{}
Which of the following statement is not ‘true’ about the above code.
Ans : Option C: Reference of parent class can accept the instance of child class but not the
instance of GrandChild class

Section 3
1. What will be the output of the below code

public class student {

String stuName="Jacklin";

void func() throws Exception{


try
{
stuName+="--";

}
catch (Exception e) {
throw new Exception();
}
finally
{
stuName+="Hello" +stuName;
}
stuName+="!!!!";
}

void disp() throws Exception


{
func();
System.out.println(stuName);
}

public static void main(String[] args) {


try
{
student student = new student();
student.disp();
}
catch (Exception e) {
System.out.println("CatchBlock");
}}}

Ans Jacklin--HelloJacklin--!!!!
Option D

2. Predict the output of the foll


public class Greeter{

public static void main(String[] args) throws Exception{


try
{
System.out.println("Greeting"+ ""+args[0]);

}catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Sam");
}

}
}

Ans : Option C Sam

3. Predict the output of the below code.


public class TestDemo{

public static void main(String[] args) {


for(int a=0;a<6;++a)
try {
if(a%3==0)
throw new Exception("Except1");
try {
if(a%3==1)
throw new Exception("Except2");
System.out.println(a);

}catch (Exception inside) {


a +=2;
}finally {
++a;
}
}catch (Exception outside) {
a+=3;
}finally {
++a;
}
}
}

Ans: Option A: 5
4.       Given
Public class Sample{
                Public static void main(String[] args) throws Exception{
                                Try{
                                                System.out.println(“In try block”);
                                                System.exit(0);
                                }catch(Exception ex){
                                                System.out.println(“In catch block”);
                                                Ex.printStackTrace();
                                }finally{
                                                System.out.println(“In finally block”);
                                }
                }
}
Predict the output?
Ans: Option B.In try block

5. Which of the following exceptions are ignored during compile time (choose any 2 option)

Option A and C
ArrayIndexOutoFBoundException
NullPointerException

Section 4
1. Identify the outcome of the given code snippet

public class Demo{

public static void main(String[] args) {


int [] arrVar = {11,22,33,44,55,66,77,88,99,109};
int position =3;
int value =7;
for(int i= arrVar.length-1;i>position;i--) {
arrVar[i]= arrVar[i-1];
}
arrVar[position]= value;
System.out.println("New Array"+ Arrays.toString(arrVar));
}
}

Ans :
Option D New Array[11, 22, 33, 7, 44, 55, 66, 77, 88, 99]

2.Which of the following are true about enums in Java? (Choose 3 correct)
I. enums can implement any other interface in java
II.   an instance of enum can be created outside of enum itself
III.   enum cant extend any other class except the abstract base class java.lang.enum
IV. enum can be used to implement singleton design pattern
Ans Options i, iii & iv

3.Predict the output of the below


public static void main(String[] args) {
String name1 ="Java";
String name2 = "Java";
System.out.println(name1==name2);
System.out.println(name1.equals(name2));
}
Ans Option A: True True

4. Given
public class App{

public static void main(String[] args) {


String s1 = new String ("smart");
String s2 =s1;
if(s1==s2) {
System.out.println("==smart");
}
if (s1.equals(s2)) {
System.out.println("equals smart");
}
}
}
Ans Option B
==smart
equals smart

Section 5
1.What will happen when the following code is executed?( Output – not sure)
public class TestDemo{

public static void main(String[] args){


List list1=new ArrayList<>();
list1.add("1");
list1.add("2");
list1.add(1,"3"); //Line1
List list2=new LinkedList<>(list1);//Line2
list1.addAll(list2); //Line3
list2=list1.subList(2,6);//Line4
list2.clear();
System.out.print(list1+ "");
}
}

Ans: [1, 3] (answer not in option)

2. Which among the following option are correct with respect to HashMap
 Override boolean equals(Object o)
Override toString()
Override int hashCode()
Override String hashCode()

Ans – option a - Override boolean equals(Object o)

3. Identify the incorrect statement as per the collection Framework hierarchy?


Ans D: LinkedHashSet Implements HashSet
4. What is the result of compiling and running this code snippet?
import java.util.Arrays;
import java.util.Comparator;

public class Demo3 implements Comparator<String>{


@Override
public int compare(String x, String y){
return x.toLowerCase().compareTo(x.toLowerCase());
}
public static void main(String[] args){
String[] values = {"JOHN","Annie","JACKLINE"};
Arrays.sort(values,new Demo3());
for (String str:values)
System.out.print(str + " ");
}
}
Ans - JOHN Annie JACKLINE

5. Predict the output of the below code snippet?


import java.util.ArrayList;
import java.util.List;

public class sam1 {


public static void main (String[] args){
List<String> list = new ArrayList();
list.add(0,"A");
list.add(1,"B");
list.add(1,"C");
for (Object object:list){
System.out.print(" " + object);
}

}
}

Ans --- A C B

Section 6:
1.What is true regarding the following code snippet

public interface StaticInterface {


      
       static void staticMethod()
       {
       System.out.println("Inside interface");
       }
}
public class StaticInterfaceImpl implements StaticInterface {
      
       public void staticMethod()
       {
       System.out.println("Inside class");
       }
       }
public class StaticDemo {
      
       public static void main(String[] args)
       {
       new StaticInterfaceImpl().staticMethod();
       }
       }
 

Ans: Option D. code will print “inside class” on execution

2. Which out of the following are true in regard to interfaces in Java


a.  An interface can contain default and static method with defined
bodies
b.  An object can be created of an interface
c.  Multiple inheritance is allowed in interface
d.  Multi level inheritance is not possible in interface

Ans Option A and  C

3. Default format of LocalDate is


Ans Option B yyyy.mm.dd

4. Given

interface Greeting{
default void greet() {
System.out.println("In Greet interface");
}

}
class GreetingDef implements Greeting{
public void greet() {
System.out.println("In GreetingDef class");
}
}

public class App {

public static void main(String str []){


Greeting obj = new GreetingDef();
obj.greet();
}

Ans:Option B- In GreetingDef class

5. The below code will generate compilation error. Select the possible options to
avoid it(Choose 2)

public interface Insurance{


  
   static void policy() {
          System.out.println("policy");
   }
 
}
public class InsuranceImpl implements Insurance{
       public void policyPayment() {   
             policy();
   }     
public class App{
       public static void main(String[] args) {
             new InsuranceImpl().policyPayment();
       }
}
 

a.       Static method of an interface can only be accessed using interfaces name
b.       Static method should always be public
c.       Static method cannot be invoked inside the non static method
d.       Policy() method of interface has to be accessed using interface name
 
Ans option A & D

Section 7:
1. What is Magic Number in java in the context of java programming best
practices?

Ans – A direct usage of number in the code.

2. Given
public class Employee {
private int empId;
private String empName;
private String designation;
private transient String dob;
}

Analyze the given code and identify the suitable comments from the below option.

Ans:
(i) Fields in non-serializable classes should not be ‘transient’
(ii) Make the Employee class as serializable

3. From the below options identify the methods and constructors in Throwable that
support checked exception?
(i) Throwable getCause()
(ii) Throwable initCause(Throwable)
(iii) Throwable (String, Throwable)
(iv) Throwable (Throwable)

Ans – (i), (iii), (iv)

4. Identify the valid code needs to be inserted in line5, assume the code is
running in

import java.util.Random;

public class Emp {


private static String id;
private Random random = new Random();
public Emp(){
//line5 if(id==null){

id = "ACC1101" + Math.abs(random.nextInt());
}
}
public String getId(){
return id;
}
}

Ans - if(id==null){

5. Select the valid code fragment according to Java coding standard?


(i) public void draw(String s){
if(s.equals("Square")){
drawSquare();
}
}
(ii) public void draw(String s){
if("Square".equals(s)){
drawSquare();
}
}

Ans: Both (i) and (ii) are valid.

Section 8:
1. Which among the following comes under Creational Design pattern?

Ans: Singleton Design Pattern

2. Which of the statements are true about design patterns?


i. There are only three design patterns defined for Java
ii. We can use each design pattern only once per application
iii. Design patterns are conceptual reusable solutions

Ans: Statement i,ii,iii

3. What changes need to be made In the following code to make the singleton pattern correct?
(choose 2)

public class Employee1 {


public static Employee1 employeeInstance;
private Employee1(){}
public static Employee1 getEmployee()
{
if (employeeInstance==null){
employeeInstance = new Employee1();
}
return employeeInstance;
}
}

Ans:
Option A &D
A. None the singleton pattern is properly implemented
D. Change the access modifier of employeeinstance from public to private

Section 9:
1. Given
//Assume all the required imports are added
import java.util.ArrayList;

import org.junit.Before;
import org.junit.Test;

public class Demo4 {


static int a = 10;
static ArrayList b = new ArrayList();
@Before
public void inint(){
a=15;
b.add(a);
}
@Test
public void test(){
a=a+20;
System.out.print(a);
System.out.println(b);
}
@Test
public void test1(){
a=a+30;
System.out.print(a);
System.out.println(b);
}

Predict the output?

Ans -
35[15]
45[15, 15]

2. Which of the following annotation must be used in a test class to run same
test again and again

Ans: @Test
3. Predict the output for the below
//Assume all the required import statements are added
import org.junit.Before;
import org.junit.Test;

import junit.framework.Assert;

public class TestDemo1 {


@Before
public void beforeTest1(){
System.out.println("in before test2");
}
@Before
public void beforeTest2(){
System.out.println("in before test1");
}
@Test
public void test(){
String a = "123";
Assert.assertSame("123",a);
}

Ans:
Test Passed as they point the same object and prints the below in console
in before test1
in before test2

ThJava Question
1.       Which of the following is not pre defined annotation in Java?
@Deprecated
@Overriden
@SafeVarags
@FunctionInterface
 
Ans: Option B(@Overriden)
2.       public class TestString3{
Public static void main(String[] args){
//insert code here//Line3
System.out.println(s)
}
}
Which of the  below code  fragment when inserted independently at line3 generate output as
498
Ans Option B
StringBuffer s = new StringBuffer("123456789").s.delete(0,3).replace(1,3,"98").delete(3,8);

3.Predict output of this


public static void main(String[] args) {

String Value1= "Hello";


String Value2= new String ("Hello");
System.out.println(Value1.equals(Value2)+""+(Value1==Value2));
String Value3= Value2.intern();
System.out.println((Value1==Value3)+""+(Value1.equals(Value3)));

Ans truefalse
Truetrue

66. Which of the following statements are true if a duplicate element obj T is added to a HashSet?

a) The element obj T is not added and add() method returns false
b) The element obj T is added successfully
c) An exception occurs during runtime
d) An exception occurs during compile time

. which of the following is incorrect regarding interfaces in Java SE8


a.all the methods are public,abstract by default
b.all the variables are public by default
c.methods can have implementation
d.its possible to hold static method

a) a and b
b) b and c
c) a,b and c
d) a only

Which of the below are NOT good practices for creating objects?
a) Lazy initialization of objects
b) Creating String literals instead of String objects
c) Creating Wrapper objects instead of primitives
d) invoking static factory methods for immutable classes

Which of the below statement indicate the need to use the factory pattern?

a) we have two classes that do the same thing


b) we only want one instance of the object to exist
c) we want to build a chain of objects
d) we don’t want the caller to depend on a specific implementations
4.What is the output when the below code is compiled and executed

Package exceptions;
Public class Demo
{
public static void main(String[] args) {

try
{
return;

}
finally
{
System.out.println("Finally");
}

 Ans : Option A:( Finally)

What is the output of the below code snippet

enum Customer
{
private CUSTID
public CUSTNAME
protected ADDRESS

Ans : D Compilation Fails


(Explanation: Enum cannot have any modifiers. They are public, static and final by default)

What is the output of the below code


package javaBasics;
public class student {

String stuName="Jackin";
void display()
{
try
{
stuName+="John";
func();
}
catch (Exception e) {
stuName+="GoodName";
}
}

void func() throws Exception{


try
{
stuName+=".......";
method();
}
catch (Exception e) {
throw new Exception();
}
finally
{
stuName+="!!!!!!";
}
stuName+="hello";
}
void method() throws Exception
{
throw new Exception();
}

void disp()
{
System.out.println(stuName);
}

public static void main(String[] args) {


try
{
student student = new student();
student.display();
student.disp();
}
catch (Exception e) {
System.out.println("CatchBlock");
}

}
} Ans Option D (JackinJohn.......!!!!!!GoodName)

What will be the output of the following code


public class Test{
public void method()
{
for(int i=0;i<3;i++) {
System.out.println(i);
}
System.out.println(i);
}
}

Ans: C. Compilation Fails

What is the result of attempting to compile and run this program


public class Customer{
public static void main(String [] args)
{
Float f1= new Float(67.65f);
Float f2= new Float(36.45f);
if(f1>f2)
{
System.out.println("f1 is bigger than f2");
}
else
{
System.out.println("f1 is not bigger than f2");
}

}
}

Ans : Option A (f1 is bigger than f2)

What is the result of the following code snippet when compiled

public class Employee {


int employeeid;
double getEmployeeid()
{

System.out.println("Employee Id");
return employeeid;

}
}

Ans A: The code will not be complied as there is no main method

Given Enum definition and java class


enum Day{
SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5),
FRIDAY(6) ,SATURDAY(7) ;
private int value;
private Day(int value)
{
this.value =value;
}

public int getValue()


{
return this.value;
}

public class Employee {


public static void main(String[] args)
{
for (Day day: Day.values()) {

//Line1
System.out.print(day.toString()+"-");

//System.out.print(day.name()+"-");

}
}

What should be [placed in line 1 to get the output as

SUNDAY-MONDAY-TUESDAY-WEDNESDAY-THURSDAY-FRIDAY-SATURDAY-

Choose one or more options

Ans : A and C

System.out.print(day.toString()+"-");

System.out.print(day.name()+"-");

What will be the output of the following code


public void method(){
for(int i=0;i<3;i++){
System.out.print(i);
}
System.out.print(i);

}
Ans: C. Compilation fails

which of the below exceptions are mostly thrown by JVM in a Java application?(Choose all that apply)
means runtime exception

a) ClassCastException
b) IllegalStateException
c) NumberFormatException
d) IllegalArgumentException
e) ExcdeptionInitializerError

Checked Exceptions are Compile time exceptions

Unchecked Exceptions are runtime exceptions

//Check Tutorial

What’s the output of the following code


public class Demo {
void main(){
System.out.println("JAVA");
}
static void main(String args){
System.out.println("Spring");
}
public static void main(String[]args){
System.out.println("Hibernate");
}
void main(Object[] args){
System.out.println("Apache Camel");
}

Ans Option A: Hibernate

Given the below code snippet, predict the correct option


public class Operator {
public static void main(String[] args){
float val1=5.3f;
float val2=2.3f;
float result= val1 %val2;
System.out.println(result);
}

Ans: Option A Code compiles, runs and produces the output 0.7000003

What is the output for the below code


public class Employee {

public final void show(){


System.out.println("show() inside Employee");
}

public class Dem011 {

public static void main(String[] args) {


Employee employee = new unit();
new unit().show1();

}
}

final class unit extends Employee {


public void show1() {
final int x=100;
System.out.println("show() inside Unit");
System.out.println(x);
}
}

Ans:Option D.
show() inside Unit
100

What is the output when we execute the below code

public class Dem011 {


static class Customer {
public void go() {
System.out.println("Inside Customer");
}
}
static class Account extends Customer {
public void go() {
System.out.println("Inside Account");
}
}
static class Branch extends Customer {
@Override public void go() {
System.out.println("Inside Branch");
}
}
public static void main(String[] args) {
Customer customer = new Account();
Branch branch = (Branch) customer;
branch.go();

}
}

Ans Option5: An exception is thrown at runtime because (Branch)Customer is incorrect

Predict the output for the below code

public class Game {

public static void main(String[] agrs) {


displayRegistration("Hockey"); //Line 1
displayRegistration("Kho-Kho", 132, 102, 36); //Line 2
}

public static void displayRegistration (String gameName, int... id) {


System.out.println("Registration for "+ gameName + ".");
for(int i=0; i<id.length; i++) {
System.out.println(id[i] + "");
}
}
}

Ans

Registration for Hockey.


Registration for Kho-Kho.
132
102
36
1. What is the output of the following code?

Class Employee {

Void disp(char c){

System.out.print(“Employee name starts with : ”+c+”.”);

System.out.print(“His experience is : 11 years. “);

Class Main extends Employee {

Void disp(Char c) {

Super.disp(c);

System.out.print(“Another employee name also starts with : ”+c+”.”);

new Employee().disp(“D”);

disp(7);

String disp (int c) {

System.out.print(“His experience is :”+c+”);

return “Bye”;

Public class Demo11 {

Public static void main (String a[]){

Employee emp = new Main();

emp.disp(“S”);

1. Employee name starts with : S. His experience is : 11 years. Another employee name also starts
with : S. Employee name starts with : D. His experience is : 11 years. His experience is : 7.
2. Employee name starts with : S. His experience is : 11 years. Another employee name also starts
with : S. His experience is 7 years
3. Employee name starts with : S. His experience is : 11 years. Another employee name also starts
with : S. Employee name starts with : D. His experience is
4. Employee name starts with : S. His experience is : 11 years. Another employee name also starts
with : S.

Predict the output of below code


public class Test {

public static void main (String a[]){

System.out.print("Implementing type Casting");


Dog d = new Dog();
BullDog bd = (BullDog) d;
bd.show();
}

class Dog{
void show(){
System.out.print("Dog");
}
}
class Cat{
void show(){
System.out.print("Cat");
}
}
class BullDog extends Dog{
void show(){
System.out.print("BullDog");
}
}

Ans tricky as runtime error and Implementing type casting also comes. But I guess
more appropriate is runtime error

RUNTIME ERROR : java.lang. ClassCastException


Implementing type CastingException in thread "main" java.lang.ClassCastException:
certificationJava.Dog cannot be cast to certificationJava.BullDog at
certificationJava.Dem011.main(Dem011.java:9)
Which code fragment can be inserted at Line 26 to display the output as “Inside
catch(RuntimeException) finally end” ?

public class Dem011 {

public static void main (String a[]){

{
try
{
method();
System.out.print("Inside try");
}
catch (RuntimeException ex)
{
System.out.print("Inside catch(RuntimeException)");
}
catch (Exception ex1)
{
System.out.print("Inside catch(Exception)");
}
finally
{
System.out.print("finally");
}
System.out.print("end");
}
}
public static void method()
{
//Line 26
}
}

Ans: Option A

throw new RuntimeException();


Predict the output of the foll

Square.java
final class Square {
private double length, breadth;
Square(double length, double breadth) {
this.length= length;
this.breadth= breadth;

Square(Square square){
System.out.println("Copy Constructor Invoked");
length =square.length;
breadth= square.breadth;
}
public String toString() {
return "(" + length +"+"+breadth+")";

}
}

Main.java

class Main{

public static void main(String args[]){


Square square1= new Square(110,115);
Square square2= new Square(square1);
System.out.println(square2);
}
}

Ans: Option A

Copy Constructor Invoked


(110.0+115.0)
Which Line fragment can be inserted in Line 1 will help to get the output as 110231(choose all apply)
package certificationJava;

public class InnerClassDemo {

private int bookid=110;

class Book
{
private int bookid=231;
private int getBookid()
{
return bookid;
}

public void main (String [] args)


{
Book book = new Book();
System.out.println(book.getBookid());
}
}

private int getBookid() {

return bookid;
//Line1

Ans : Option 2 and Option 4


InnerClassDemo innerClassDemo = new InnerClassDemo();
InnerClassDemo.Book book = innerClassDemo.new Book();
System.out.printf("%d",innerClassDemo.getBookid());
book.main(args);

and

InnerClassDemo innerClassDemo = new InnerClassDemo();


Book book = innerClassDemo.new Book();
System.out.printf("%d",innerClassDemo.getBookid());
book.main(args);

Which of the below option fails at Line 7(choose all that apply)

Employee.java
public class Employee {

static final int empid =1101;

SuperDemo.class

class Unit extends Employee{

int empid =1102;

void display()
{
//Line7
}
}
class SuperDemo {
public static void main(String [] args)
{

Unit unit = new Unit();


unit.display();

}
Options
i. System.out.println("Maximum Speed"+super.empid);
ii. System.out.println("Maximum Speed"+ new Employee().empid);
iii. Employee emp1 = new Employee();
System.out.println("Maximum Speed"+ new Unit().empid);
iv. System.out.println("Maximum Speed"+ Employee.empid);

All 4 options works fine. Not sure if question is wrong or what

Given

The below code fragment can be inserted at Line 1 and Line 2.What will be the output?
ConstructorDemo1 constructorDemo1=new ConstructorDemo1(1101,"Jacklin");
ConstructorDemo1 constructorDemo2=new ConstructorDemo1(1102,"John",25);

class ConstructorDemo1 {
private int id;
private final String name;
static final int age=22;
ConstructorDemo1(int i,String n){
id=i;
name=n;
}
ConstructorDemo1(int i,String n,int a){
id=i;
name=n;
}
void display(){
System.out.println(id+" " +name+" "+age);
}
public static void main(String args[]){
//Line1
//Line2
constructorDemo1.display();
constructorDemo2.display();
}
}

Ans Option B
1101 Jacklin 22
1102 John 22

Predict the output of the below code


public class InnerClassDemo {

InnerClassDemo()
{
System.out.print("InnerClassDemo Constructor");
}

Demo.java

class Demo {

Demo()
{
System.out.println("Demo Constructor");
}
public void disp()
{
System.out.print("Simple Class");
}
public static void main(String[] args)
{
InnerClassDemo innerClassDemo=new InnerClassDemo();
innerClassDemo.createDemo();
}
void createDemo()
{
(new Demo() {}).disp();
}

Ans : Option A : Compilation fails

Predict the output


class Main{

public void display(int i) {

System.out.println("Inside First");
}
public void method(int i,int j) {

System.out.println("Inside Second");
}
public void method(int... k) {

System.out.println("Inside Third");
}

public static void main(String args[]){

new Main().method(110);
new Main().method(110,210);
new Main().method(110,210,310);//Line1
new Main().method(110110,210,310,410);//Line2

Ans:

Inside Third
Inside Second
Inside Third
Inside Third

Predict the output


public class Book {
int bookid = 2356;

public class Book1 extends Book{


int bookid = 1167;

public class Book2 extends Book1


{
int bookid = 2378;
void display()
{
System.out.println(super super.bookid);//Line10
System.out.println(super.bookid);//Line11
System.out.println(bookid);
}

class Demo {

public static void main(String[] args)


{
Book2 book2 = new Book2();
book2.display();
}

Ans: A. Compilation Fails because of an error in Line10

When the following code is inserted in Line 6. Whats the output


Apple apple = (Apple)typeCastDemo;

class Apple {

public class TypeCastDemo {


public static void main(String[] args)
{
TypeCastDemo typeCastDemo = new TypeCastDemo();
//Line6

Ans Option C.

Compilation fails as typecast cant be done from TypecastDemo to Apple

What code fragment can be inserted at Line3 to enable the code to print188.22
enum Fruits{

APPLE,
MANGO,
STRAWBERRY,
LICHI;

double claculate(double a, double b) {


switch(this) {
case APPLE:
return a+b;
case MANGO:
return a-b;
case STRAWBERRY:
return a*b;
case LICHI:
return a/b;
default :
throw new AssertionError("Unknown input"+this);

public class EnumDemo {


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

Ans : Option A
double res = Fruits.MANGO.claculate(298, 109.78);

Whats the output


public class Parent {

void message()
{
System.out.println("Inside parent class");
}
}
public class Derived extends Parent{

void message()
{
System.out.println("Inside derived class");
}
void display()
{
message();
super.message(); //Line1
}
}

class SuperDemo {
public static void main(String [] args)
{

{
Derived derived=new Derived();
derived.display(); //Line2
}

Ans: Option D.
Inside derived class
Inside parent class
What is the result of attempting to compile and run this program
public class Bank extends Exception{

public class Customer extends Bank {

public class ExceptionDemo {

public static void main(String args[]) {

try
{
throw new Customer();
}

catch (Bank bank) {

System.out.println("Bank catch Block");


}

catch(Customer customer) {

System.out.println("Customer catch Block");


}
}

Ans : Option C. Compilation error because Customer class exception is not throwable.

Whats the output of the following


public class Demo extends Book {
int bookid =4567;

public int getValue() {


return bookid;
}

public void call() {


System.out.println(getValue());
System.out.println(super.getValue());

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

Book book = new Book();


book.call();//Line3
super.call();//Line4

}
}

Book.java

public class Book {


int bookid = 17897;

public int getValue() {


return bookid;
}

Ans: Option D. Compilation fails because of an error in line 3 and line 4

2. What is the output of the following code ?


Package exceptions;

Import java.io*;
Public class ExceptionDemo{
Static class Car implements AutoCloserable{
Public void close(){
System.out.print(“Automatic Door Close”);
}
}
Static class carWindow implements Closerable{
Public void close(){
System.out.print(“CarWindow”);
throw new RuntimeException();
}
}

Public static void main(String[] args){


Try(Car car=new Car();
CarWindow carWindow=new CarWindow()){
System.out.print(“Inside try block”);}
}
Catch(Exception e){
System.out.print(“Inside catch block”);
}
Finally{
System.out.print(“finally”);
}
}
}

a. Automatic Door close CarWindow Inside try block inside catch blockfinally
b. Automatic Door Close CarWindow Inside catch blockfinally
c. Inside try blockCarWindowAutomatic Door CloseInside catch blockfinally
d. An exception is thrown at run time
e. Compilation fails

Ans : c. Inside try blockCarWindowAutomatic Door CloseInside catch blockfinally

60. Given:
Public class ExceptionDemo1{
Static class Car implements AutoCloseable{
Public void close(){
System.out.print(“Car door close”);
Throw new RuntimeException();
}
}
Static class CarWindow implements Closeable{
Public void close(){
System.out.println(“Car window close”);
Throw new RuntimeException()
}
}
Public static void main(String[] args){
Try{
//Line 1
}
Catch(Exception e){
System.out.println(“Catch exception”);
}
Finally{
System.out.print(“”finally”);
}
}
}
Which of the below code can be inserted at Line1 to display THE OUTPUT AS “try block finally” (Choose
all that apply)

A)Car car=new Car();


CarWindow carWindow=new CarWindow();
System.out.print(“try block”);

B)Car car=new Car();


System.out.print(“try block”);

C)Car car=new CarWindow())


System.out.print(“try block”);

D)system.out.print(“try block”)

. Which two statements are true for a two-dimensional array?


A.It is implemented as an array of the specified element type
B.Using a row by column convention, each row of a two-dimensional array must be of same size
C.At declaration time,the number of elements of the array in each dimension must be specified
D.All the methods of the class Object may be invoked on the two-dimensional arrary

a) Option (A) and (B)


b) Option (A) and (B)
c) Option (B) and(C)
d) Option (C) and (D)

Which of the below code fragment needs to be inserted at Line12 to display the output as 15.
public class ExceptionInClass {
int data=10 ;
void calculate() throws Exception
{
try
{
data++;
try
{
data++;
// Line12
}

catch(Exception ex)
{
data++;
}
catch(Exception ex)
{
data++;
}
}
}

void display()
{
System.out.println(data);
}
public static void main(String[] args) throws Exception
{
ExceptionInClass exceptionInClass = new
ExceptionInClass();
exceptionInClass.calculate();
exceptionInClass.display();
}

Ans: None of the above. If not write answer as option A

What is the output when the below code is compiled and executed?
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo1{


public static void main(String[] args) {
("x*y");
Matcher match=pattern.matcher("y");
Boolean boolean1=match.matches();
System.out.println(boolean1);
}
}

Ans: Option A True

Output of below code is


class Light{
Boolean isOn;

void turnOn(){
isOn=true;
}

void turnoff(){
isOn=false;
}

}
class LightDemo{
public static void main(String[]args){
Light light1=new Light();
Light light2=new Light();
light1.turnOn();
System.out.println("light1 is on");
light1.turnoff();
System.out.println(light1.isOn);
System.out.println(light2.isOn);
}
}

Ans: True

False

Null

What will be the output of the code given below?


public class ABC{

public static void main(String[]args){


Boolean flag=false;
if (flag = true){
System.out.println("true");}
if (flag = false)
{
System.out.println("false");
}}}

Ans Option A. True

What will be the output of the following code


public class Test{
public void method()
{
for(int i=0;i<3;i++) {
System.out.println(i);
}

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

}
Ans: C. Compilation Fails

What error do we get when we compile the below code


public class Main{

static int[] x;
static{
x[0]=102;}
public static void main(String[]args){
System.out.println(x);
}

Ans java.lang.ExceptionInInitializerError

What is the output for the below code

public class VarArgsDemo{

static void func(int...x)


{
System.out.println("Number of arguments "+x.length);

for(int i:x)
System.out.print(i+"");
System.out.println();
}
void func(int a) //Line1
{ System.out.println("one"); }

public static void main(String[]args){


new VarArgsDemo().func(150);
func(11, 12, 13, 14);
func(); }
}

Ans:Option B
one
Number of arguments 4
11121314
Number of arguments 0

How many objects are eligible for garbage collection after executing line8.
public class Employee {

double salary;
public static void main(String[]args){
Employee employee1=null;
Employee employee2=null;
employee1= new Employee();
employee2= new Employee();
employee1= new Employee();
Employee employee3=null;
employee1= employee3=null; //Line8
System.out.println("Hello World");
}

Ans :3 objects

Which statements are true about the following code snippet?(choose all that apply)

Public class Developer{}


Public class Employee{
Public String empName;
}

Public class Tester extends Employee{


Public Developer developer;
}

Public class Testing extends Tester{}

a. Testing has a empName


b. Testing has a Developer
c. Testing is a Developer
d. Testing is a Employee
e. Tester is a Testing
f. Employee has a Developer

Ans : d & a

Observe the below code snippet:


public class Tree extends BasePlant{

public void growFruit(){}


public void dropLeaves(){}

public class BasePlant {

private String name;


public BasePlant(String name){
this.name=name;
}

public String getName(){


return name;
}

Which of the following statement is true?(choose all that apply)

a. The code will be compiled without any changes


b. The code will be compiled only if the below code is added to the Tree class
Public Tree() {super(“Plant”);}
c. The code will be compiled only if the below code is added to the BasePlant class
Public BasePlant() {Tree(); }
d. The code will be compiled only if the below code is added to the BasePlant class
Public BasePlant() {this(“Plant”); }

Ans : b & d
Predict the output

Apple.java
public class Apple {

public void color(){


System.out.println("Red");
}
}

Mango. Java

public class Mango extends Apple{

@Override
public void color(){
System.out.println("Yellow");

}
public static void main(String[]args){
Apple apple=new Mango(); //Line1
apple.color();//Line2
}

Ans: Yellow

Given:

public interface interfaceDemo{


//Line1
}

Select the suitable code fragment can be inserted at Line1(choose all that apply)

a. void display(int x);


b. void display(int x) {}
c. public static void display(int x){}
d. default void display(int x);
e. public interface Demo{}

Ans : a,c and e


Analyze the code and select the suitable outcome
class Apple {

private Apple() {

System.out.println("Apple constructor");

void display(){
System.out.println("Apple constructor");
}
}

public class Main {

public static void main(String[]args){


Apple apple=new Apple(); //Line2
apple.display();
}

Ans: Option D: Unresolved compilation problem: The constructor Apple() is not visible
Output of the below code
public class Demo {
static int x=232;
int y=135;
public void display(){
System.out.print("Inside Demo");}
public static void staticMethod(){
System.out.print(x); //Line 8
}

public static void main(String[]args)


{
Demo.staticMethod();//Line 13
Demo demo=new Demo();
demo.staticMethod(); //Line15
staticMethod();
demo.display(); //Line 16
}

Ans : Option B

232232232Inside Demo

Check line13. If its not Demo.staticMethod(); then answer will be 232232Inside Demo

Output of the below code


public class Demo {

public static void main(String[] args){


try{
throw 110;
}

}
catch(int ex){
System.out.println("Caught Exception" + ex);
}
}

Ans: Compilation Fails

Predict the output of the below


public class TestDemo {

public static void main(String[] args){


int sum, a=10, b=10;
try{
System.out.println(sum=a/b);
return; //Line 1
} catch(ArithmeticException | Exception e){ //Line2
System.out.println(e.getMessage());
}finally{
System.out.println("in finally");
}
}
}

Ans: Compilation fails because of the error in Line2

What are the different types of memory areas used by JVM(choose two)?

1.Class

2.Heap

3.Stack

4.Queue

JVM in java is a

1.Debugger

2.Assembler

3.compiler

4.Interpreter

132. What is magic number in java in the context of java programming best practices?

1.A number which gets printed on the console

2.A direct usage of the number int the code

3.A number which magically disappears from the code


4.A number which is generated through error

What is the output of the below code


public class person {

public person(String name){


System.out.println(name);
}

public class student extends person{

public student(){ //Line 8


System.out.println(" Student");
}

public static void main(String[] args) {// Line 11


new person("Jacklin");
}

Ans: Compilation fails because of an error in Line 8

3. Given:
public abstract class Employee {

private int empId;

private int salary;

public abstract void display();

public void setValues(int empId, int salary){

this.empId = empId;

this.salary = salary;

Which of the following classes provide the right representation of the child class of Employee class?

1) public abstract class Child extends Employee {


private int z;
}

2) public class Child implements Employee {


private int z;
}

3) public class Child extends Employee {


private int z;
public void display();
}

4) public class Child extends Employee {


private int z;
public void display() {
/* code here */
}}

Ans : 4) public class Child extends Employee {

private int z;
public void display() {
/* code here */
}}
4. Given an abstract Class Customer as below:

public abstract class Customer

{
public abstract String getCustomerType();

Select a Valid implementation of getCustomer Type method in another class, from the below options:

1) abstract class C1 extends Customer{


public string getCustomer Type()
{ return “Premium”;
}
}

2) Customer customer = new Customer(){


public String getCustomerType()
{ return “Premium”;
}
}

3) class C1 extends Customer{


public String getCustomerType()
{ return “Premium”;
}
}

4) new Customer(){
public String getCustomerType()
{ return “Premium”;
}
}

Ans : 3) class C1 extends Customer{

public String getCustomerType()


{ return “Premium”;
}
}

Output of the following


class Customer{
int customerId = 11201;
Customer() {
customerId = 11240;
}
}
class Main {
public static void main(String args[]){
Customer customer = new Customer();
System.out.println(customer.customerId);
}
}

Ans: Option B 11240

Code to be written to get the output as below

False

Simple

Demo

For

Regular

Expressions

Using

Pattern

Matching
public class RegExDemo {
public static final String string1="Simple demo for "+"regular expressions"+"
usingpatternmatching";
public static void main(String[] args){
//Line 1
//Line2
}

Ans: Option 1

System.out.println(string1.matches("\\t"));
String[] splitString=(string1.split(" "+""));
//(String1.split(\\s+)) not working in my computer so did like this
for(String string: splitString){
System.out.println(string);
}
System.out.println(string1.replaceAll("\\S","\t"));

What is the result of attempting to complete and run this program?


public class Demo {
public static void main(String[] args){
String c="a";//Line 3
switch(c) {
//Line4
case 65 ://Line5
System.out.println("One");
break;
case"a"://Line6
System.out.println("two");
case 3://line 10
System.out.println("three");
break;
}
}

Ans:D Computation fails because of an error in Line 5 and Line 10

Select all possible options that are valid among the following Enums can be defined inside____

a) An interface
b) A class {Multiple choice question}
c) A static Context
d) A method

Which code fragment can be inserted at Line 1 to enable the code to print as “Number of Days =25”
class Demo {
public static void main(String[] args)
{
int monthValue=2;
int yearValue=4000;
int numberOfDays=10;

switch(monthValue) {

case 1: case 3: case 5:


case 7: case 8: case 10:
case 12;
numberOfDays=31;
break;
case 4: case 6:
case 9: case 11:
numberOfDays=28;
break;
case 2:
//Line1

numberOfDays=25;
else
numberOfDays=28;
break;

default:
System.out.println("Number of Days =" +numberOfDays);

}
}

Ans: Option not clear. Either one can come. Make sure assignment operator is there(= =)
if((yearValue% 4 ==0) &&
(yearValue% 100==0)
||(yearValue% 400==0))

Or

if((yearValue% 4 ==0) ||
(yearValue% 100==0)
||(yearValue% 400==0))

81. Identify which of the following class breaks its input into tokens using a whitespace pattern?

a. InputStreamReader
b. Console
c. Scanner
d. Buffered Reader
e. DataInputStream

What is the output when below code is compiled and executed.


import java.util.regex.Pattern;
public class RegExDemo2 {
private static final String String1="";
private static final String String2="one two three four five";
public static void main (String[] args){
Pattern pattern=Pattern.compile(String1);//Line 7
String[] strArr=pattern.split(String2);//Line 8
for(String str:strArr){
System.out.println(str);
}}
}

Ans : Option C (if pattern.compile and pattern.spilt don’t have dot means then
compilation error)

C)one
two
three
four
five

What is the output of the below code


package certificationJava;

public class ABC {


public static void main(String args[]){
Boolean flag=false;
if(flag=true){
System.out.println("true");
}
if(flag==false){
System.out.println("false");
}
}
}
Ans: Option A . True

Which is the correct code fragment to be inserted at Line 1to execute the code to print count starts
from 111,112,113….
public class Demo2 {
public static void main(String[] args){
int[]X={111,112,113,114,115,116,117,118,119,110};
//Line1
System.out.println("count is"+i);
}
}
}

Ans : Option B
for(int i:X){

Predict the output of the below


public class Calculator {

int a=123;
int b=200;
public void display(){
System.out.println("a"+a+"b"+b+"");
}}
public class CalculatorDemo {
public static void main(String[] args)
{
Calculator calculator1=new Calculator();//Line1
Calculator calculator2= Calculator1//Line2
calculator1.a+=1;
calculator1.b+=1;
System.out.println("calculator1 values");
calculator1.display();
System.out.println("calculator2 values");
calculator2.display();
} }

Ans : D. Compilation fails because of error in Line2

Output of the following


class Demo{
public static void main(String[] args){

int i1=0;
int[] j={11,111,14,19,116,215}; //line4
for (int i1:j) //line5
System.out.printf("%d",i1);
}

Ans :Option C: compilation fail because of an error in line5


Output of the following
abstract class Customer {

public int custId;


Customer()
{
custId=23456;
}
abstract public void setId();
abstract final public void getid();//Line11
}

class Demo extends Customer{


public void setId(int custId)
{
this.custId=custId;
}
final public void getid()//Line9
{
System.out.println("Customerid"+custId);
}
public static void main(String[] args)
{
Demo demo=new Demo();
demo.setId(1102);
demo.getid();
}}
Ans :

a) compilation fails because of an error in Line9


b) compilation fails because of an error in Line11
Output of the below code

public class Employee {

public final void show(){


System.out.println("show()inside Employee");
}
}

final class Unit extends Employee{


public void show1(){ //Line1
final int x=100;
System.out.println("show()inside Unit");
System.out.println(x);
}
}

public class Demo11{


public static void main(String[] args){
Employee employee=new Unit();
new Unit().show1();
}
}
Ans:Option D

show()inside Unit
100

Given
Class Parent{
}
Class Child extends Parent{
}
Final class GrandChild extends Child{
}
Which of the following statement is not true about the above code?

a) The above code represents the multi-level inheritance with the two level
b) The GrandChild class can Access the protected and public members of the parent and child class
c) Instance of parent class can accept the reference of the child class but not the reference of
GrandChild class
d) The GrandChild class can override the methods of both Parent class and Child class

In the below code snippet identify which of the following method compares the given values and return
an int which tells lesser or greater

public class WrapperClassDemo {

public static void main(String aa[])


{
int x=90;
Integer i1=new Integer(x);
int y=90;
Integer i2=new Integer(y);

System.out.print(i1.compareTo(i2)+""+Integer.compare(i2,i1)+""+i1.equals(i2)+""+
(i1==i2));
}
}

a) Compare()
b) Equals()
c) compareTo()
d) ==
Output of the below code

public class TestDemo {


public static void main(String[] args){
Integer n1=new Integer(100);
Integer n2=new Integer(100);
Integer n3=127;
Integer n4=127;
Integer n5=128;
Integer n6=128;
int n7=129;
int n8=129;
System.out.print(n1==n2);
System.out.print(n3==n4);
System.out.print(n5==n6);
System.out.print(n7==n8);
}
}

Ans A: falsetruefalsetrue

Output of the following

public static void main(String args[]) {

TreeSet<String> treeset=new TreeSet<String>();


treeset.add("first");
treeset.add("First");
treeset.add("Second");
System.out.println(treeset.ceiling("Fir"));
}

Ans : Option C

First

If <String> not defined then compilation error comes

Output of the following

public class TestDemo {


public static void main(String[] args){
ArrayList Strings=new ArrayList();
Strings.add("aAaA");
Strings.add("AaA");
Strings.add("aAa");
Strings.add("AAaa");
Collections.sort(Strings);
for(string:Strings){
System.out.print(string);
}}}

Ans: Option A Compilation Fails

Output of the following

public class person {


private final String name;

public person(String name){


this.name=name;
}

public String toString(){


return name;
}
}

import java.util.TreeSet;
public class Group extends TreeSet {

public static void main(String[] args){


Group g=new Group();
g.add(new person("Hans"));
g.add(new person("Jane"));
g.add(new person("Hans"));
System.out.println("Total"+g.size());
}

public boolean add(Object o){


System.out.println("Adding"+o);
return super.add(o);
}
}

Ans : Option A

a) Adding Hans
An exception is thrown at the runtime(java.lang.ClassCastException)

Output of the following

public interface StaticInterface {


static void staticMethod()
{
System.out.println("Inside interface");
}
}

public class StaticInterfaceImpl implements StaticInterface {

public void staticMethod()


{
System.out.println("Inside class");
}
}

public class StaticDemo {

public static void main(String[] args)


{
new StaticInterfaceImpl().staticMethod();
}
}

Ans: Option D. code will print “inside class” on execution

Inside class

Output of the following

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Formatting {


public static void main(String[] args)
{
LocalDate date=LocalDate.of(2016,11,13);

DateTimeFormatter formatter= DateTimeFormatter.ofPattern("dd/MMM/YYYY");


System.out.println(date.format(formatter));
}
}

Ans: Option D: 13/Nov/2016 will be printed


13/Nov/2016

Predict the output

public interface Interface1 {


default void method1()
{
System.out.println("Inside default method");
}

public interface DefaultExtends extends Interface1{


default void method1()
{
System.out.println("Default method redefined");
}
}

public class InterfaceWithDefaultMethod implements DefaultExtends{


public static void main(String[] args)
{
InterfaceWithDefaultMethod defaultExtend=new
InterfaceWithDefaultMethod();//Line4
defaultExtend.method1();//Line5
}
}

Ans: Option B

Default method redefined

What happens when default keyword is removed from the below code snippet

public interface Interface1 {

default void method1()


{
System.out.println("Inside default method");
}

a.method cannot be overridden in the implementing classes


b.method can be overridden in the implementing classes
c.method cannot be given body in the interface
d.compilation error occurs

a) a and b
b) a,b and c
c) c and d
d) b and c

Select the valid code fragment according to java coding standard?

1) public void draw(String s){


if(s equals(“Square”){
drawSquare();
}
if(s.equals(“Rectangle”)){
drawRectangle();
}
}
2) public void draw(String s){
if(“Square”.equals(s){
drawSquare()
}
if(“Rectangle”.equals(s)){
drawRectangle();
}
}
only option(1) is valid
only option(2) is valid
Both(1) and (2) are valid
Both(1) and (2) are invalid

Whats the output of the below


public class Ex1 {
public String formatiniput(String i){
if(i.trim().length()==9){
StringBuilder s1=new StringBuilder();
s1=s1.insert(0,"+1(");
s1=s1.insert(6,")");
s1=s1.insert(10,"-");
return s1.toString();
}
return null;
}
public static void main(String args[]){
Ex1 ob=new Ex1();
String I;
ob.formatInput(i);
}
}

a) compilation fails at Line3


b) Compilation fails at Line 6
c) Null pointer exception will be thrown if the value of I is null
d) Compilation fails due to error in Line7
// I got below compilation error

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

Consider the below code snippet


Locate locate=new Locate(“da”,”DK”);
NumberFormat numberFormat=NumberFormat.getInstance(locate);
String number=numberFormat.format(100,99);
system.out.println(number);

Here NumberFormat.getInstance() follows which design pattern?


a) Factory method pattern
b) Singleton pattern
c) Abstract Factory pattern
d) Builder pattern

Output of the following


public class TestDemo {

static int a=0;


static ArrayList b;

@BeforeClass
public static void beforeClass(){
a=10;
b=new ArrayList();
}
@BeforeMethod
public void int1(){
a=15;
b.add(a);
}
@Test
public void test(){
a=a+20;
System.out.print(a);
System.out.println(b);
}
@Test
public void test1(){
a=a+30;
System.out.print(a);
System.out.print(b);
}
}

Predict the output?


a) 35[15]
45[15,15]
b) 35[15]
65[15,15]
c) 35[15]
45[15]
d) 35[15]
65[15]
e) 35[15]
65[30]

Output of the below code snippet


public class Test {

public static void main(String[] args){


int [][] x;
x=new int[3][4];
for(int i=0;i<3;i+=2){
for(int j=0;j<4;j++){
x[i][j]=i+j;
System.out.print(x[i][j]+"");
}
}
}
}
Ans : Option B
01232345

Output of the foll

public class Pet {


public void displayName(){
System.out.println("Inside Pet");
}
}

public class Dog extends Pet{

public void displayName(){


System.out.println("Inside Dog");
}
}

class Demo{
public static void main(String[] args){
Pet pet=new Dog();
pet.displayName();
}
}

Ans Option D: Compilation Fails.

Output of the following

public class Hello {


public static void main(String[] args){
String s="How\"are\"you?";
System.out.println(s);
}
}

Ans: Option A
How"are"you?

Output of the following


public class WrapperClassDemo {
public static void main(String args[]) {

Integer intWrapper=Integer.valueOf("12345");
Integer intWrapper2=Integer.valueOf("11",2);
Integer intWrapper3=Integer.valueOf("E",16);
System.out.println(intWrapper+" "+intWrapper2+" "+intWrapper3);
}
}

Ans: Option C

12345 3 14

Predict the output of the following

public class Demo11{


public static void main(String args[]) {
Set numbers=new HashSet();
numbers.add(new Integer(45));
numbers.add(88);
numbers.add(new Integer(77));
numbers.add(null);
numbers.add(789L);
Iterator iterator=numbers.iterator();
while(iterator.hasNext())
System.out.print(iterator.next());
}
}

Ans: Option F

null789884577

Which of the below code has to be inserted at Line1, to sort the keys in the props HashMap variable?
public class Demo11{
public static void main(String args[]) {
HashMap props=new HashMap<>();
props.put("key45","some value");
props.put("key12","some other value");
props.put("key39","yet another value");
Set s=props.keySet();
//Line1
} }

Ans: Option B. Collections.sort(s);


Output of the following
public static Collection get(){
Collection sorted=new LinkedList();
sorted.add("B");
sorted.add("C");
sorted.add("A");
return sorted;
}
public static void main(String[] args){
for(Object obj: get()){
System.out.print(obj+".");

}
}

Ans : Option B
B.C.A.

Output of the following

public static void main(String[] args){


TreeSet tset=new TreeSet();
tset.add(new item());
TreeSet b=tset;
}
}

Ans : Option A. Compilation Fails.

Which of the following code snippet can be inserted at line1 to display the output as

76
Hello
class Apple<A> {
A obj;
Apple(A obj)
{this.obj=obj;
}

public A getObject()
{return this.obj;

} }
class Main{
public static void main(String[] args){
//Line1
}
}

Ans :Option A and Option B


Apple apple=new Apple(76);
System.out.println(apple.getObject());
Apple appleObj=new Apple("Hello");
System.out.println(appleObj.getObject());

82. Refer the below code snippets and predict the outcome?

Public class RepeatingAnnotations{


@Retention(RetentionPolicy.RUNTIME)
public @interface Chocolates{
Favourite[] value() default();
}

@Favourite(“Diary Milk”)
@Favourite(“Kit Kat”)
@Favourite(“5 star”)
@Favourite(“Galaxy”)
public interface Chocolate{
}

@Repeatable(value=Chocolates class)
Public @interface Favourite{
String value();
}

Public static void main(String[] args){


Favourite[] a=Chocolate class.getAnnotationsBy.Type(Favourite.class);
Chocolates chocolates=Chocolate class.getAnnotation(Chocolates.class); //Line5
for(Favourite favourite: chocolates value()){
System.out.println(favourite.value()); } } }

a. Nothing will be displayed


b. null will be printed
c. Runtime exception will be thrown at Line 5
d. Dairy Milk
Kit Kat
5 Star
Galaxy

Output for thje following


public class RepeatingAnnotations {

@SuppressWarnings("all") //line1
@SuppressWarnings("deprecation") //line2
public void over()
{
new Date().setDate(00); } }

Ans: Option B.

Compilation will not be successful as @SuppressWarnings annotation is non-repeatable in nature

Output of the following


public class TestDemo {
public static void main(String[] args){
LocalDateTime date1=LocalDateTime.of(2017,Month.FEBRUARY,
11, 15, 30); //Line1
LocalDateTime date2=LocalDateTime.of(2017, 2, 12, 10, 20);

System.out.println(date1.compareTo(date2));
}
}

Ans Option A -1 will be printed as execution result


Predict the output
class Apple {

int quantity;
}

class Main{
public static void main(String[] args){

Apple apple;
System.out.println("apple quantity");

}
}

Ans: Option 5: Apple Quantity

Output of the following


public class TestDemo {
private static Object staticObject;
public static Object createStaticObject(){
if(staticObject==null){
staticObject=new Object(0);
}
return staticObject;
}
}

What changes are required in the above code for successful execution?

1.The method createStaticObject should be synchronized

2.The method createStaticObject should be private

3.The staticObject reference should not be static

4.The method createStaticObject should not return Object type

Output of the following


public class TestDemo {

public static void main(String[] args)


{
LocalDate date=LocalDate.of(12,11,2017);
System.out.print(date);
}
}

Ans: Option D: Exception will be raised as date not in range

Output of the following


public class Demo
{
public void division(int x,int y){
try{
int z=x/y;
}
catch(Exception e){
System.out.print("Arithmetic Exception");
}
finally{
System.out.print("finally block");
}
}
public static void main(String[] args)
{
Demo demo=new Demo();
demo.division(0,8);
}
}

Ans: Option 2. finally block

Output of the below code


public class Demo
{
void display()
{
System.out.println("x=*+x+*y=*+y");
}

public static void main(String[] args)


{
Demo thisDemo=new Demo();
thisDemo.get().display();
}
}

Ans: C . Compilation Fails


Output of the following
public class TestDemo {
static void myCode() throws MyException{
try{
throw new MyException("Test exception");
}
catch(Error|Exception ex){
System.out.print("Inside Error and Exception");
}
}

public static void main(String[]args)throws MyException{


try{
myCode();
}
catch(Exception ex){
System.out.print("Inside Exception");
}
}
}

Ans Option A

Prints Inside Error and Exception

Output of the following

public class ThisDemo


{

int x;
int y;
ThisDemo(){
x=45;
y=56;
}
ThisDemo get() //Line1
{
return this;
}

void display()
{
System.out.printf("x=*+x+*y=*+y");
}

public static void main(String[] args)


{
ThisDemo thisDemo=new ThisDemo();
thisDemo.get().display();
}
}
Ans: will know answer based on syso only

I got answer as x=*+x+*y=*+y

public class student {

private School school;


private StudentDetails stuDetails;
private Fees fees;

public MarksHistory marksHistory(Marks marksDetails){


//computation
}
}

Ans: Lazy Initializtion

Output of the following

public class Demo11{


public static void main(String[]args){
Parent obj =new Child();
obj.display();
}
}

public class Parent {

public void display(int a){


System.out.println("Parent Method");
}

public class Child extends Parent {

public void display()


{ System.out.println("Child Method");
}
}

Ans: A: Compilation Fails

Predict the output

public class Manager extends Employee {

public void someManagerMethod(){


//…
}
}

public class Officer extends Employee {


{
//….
public void someMethod(Employee e){
Manager m=(Employee)e ; //Line 12
m.someManagerMethod();
}
}

public class Demo {

public static void main(String s){


Officer obj=new Officer();
obj.someMethod(new Officer()); //Line 19
}
}

Ans: Option 1:Compilation fails because of an error in Line 12

Output of the following

public interface Demo1 {


public void display(String points);

}
public class Demo2 implements Demo1{
public void display(String points){};
}

public class Demo3 {


public Demo1 disp(){
return null; //more code here
}
public String displayValue(){ //Line6
return null;
//more code here
}
}

public class Demo4 extends Demo3{


public Demo2 disp(){
//more code here
return null;
}
private String displayValue(){
//more code here
}
}

Ans: Option C. compilation of class Demo4 will fail because of an error in line6

Which of the code segment is written using best practice

List list;
1. public List getList{
if(list.size()==0)
return null;
else
return list;
}

2. Integer i1=new Integer(11);


Integer i2=new Integer(11);
System.out.println(i1==i2);

3. String[] str=new String[]{"Hi","Hello","Welcome"};


List strList=Arrays.asList(str);
for(iterator itr=strList.iterator();itr.hasNext();){
System.out.println(itr.next);
}

Ans : Code 2 only is valid

144. //Assume that the first two of three test cases fail in “Testclass”

// Assme all the required import statements are added

Public class testrunner{

Public static void main(String [] args){

Result result = junitcore.runclasses(testclass.class)


For (Failure failure : result.getfailures()){

System.out.println(result.wassuccessful());

1) False
2) True
3) False false true
4) False false false

Output of the foll


public class collectionsDemo{
public static void main(String argv[]){
ArrayList arrList=new ArrayList();
ArrayList arrListStr=arrList;
ArrayList arrListBuf=arrList;
arrListStr.add(1,"SimpleString");//line6
StringBuffer strBuff=arrListBuf.get(0)://line7
System.out.println(strBuff.toString());//line8
}
}

Ans: Option C.Compilation fails because of error in Line7

Output of the following


public class StringTest {

public static void main(String[] args){


String joinString=String.join(".","java","programming","course");
String s1="JAVA",s2="java",s3="Java";
s1.toLowerCase();
s3=s3.replace("J","j");
System.out.println(joinString);
System.out.println(s1.equals(s2)+","+(s2==s3));
}
}

Ans Option D:

java.programming.course
false,false
Output of following
public interface DefaultMethodInterface1 {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface1");
}
}

public interface DefaultMethodInterafce2 {


default public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}

public class TestDemo implements DefaultMethodInterface1, DefaultMethodInterafce2{

public static void main(String[] args){


DefaultMethodInterface1 defMethln=new TestDemo();
defMethln.defaultMethod();
}
}

Ans: Compilation fails

. Which of these statements compile?(chose at that apply)

checkbox

1.HashSet hs=new HashSet();

2. HashSet set=new HashSet();


3.List list=new Vector();

List values=new HasgSet();

List objects=new ArrayList();

Map hm=new HashMap();

Output of the foll


public class TestDemo {
public static void main(String[] args){
List list1=new ArrayList();
list1.add("1");
list1.add("2");
list1.add("3");
List list2=new LinkedList(list1);
list1.add(list2);
list2=list1.subList(2,5);
list2.clear();
System.out.print(list1+"");
}
}

Ans: Option 1

the program complies successfully and throws exception during runtime


Section 1:

1. Which of the following OOP terminology associated with java……. Employee has address

Ans - Inheritance

2. What is the result when the following code is compiled and executed

public class Test {


Long a; //Line1
long b;
public Test(long c){
b=a+c; //Line 2
System.out.println(b);
}
public static void main(String[] args){
new Test(new Long(10L));

Ans: Null pointer exception in Line 2 as variable a is not

3. Given

class Movie implements Comparator<Integer> {


public int comparator(Integer o1, Integer o2){
return o2.compareTo(o1);

@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return 0;
}
}
class MovieApp {
public static void main(String[] args){
Integer mov[] = {2019,2017,1989,1994};
Arrays.sort(mov,new Movie());
for (int i:mov){
System.out.print(i+" ");
}
}

Ans – c
2019 2017 1989 1994

4. Identify the output:

public class MyDemo {


public static void main(String[] args){
int i =5;
switch(i){
case 1:
System.out.println("One");
break;
case 2:
//Line 1
case 3:
//Line 2
System.out.println("Two and Three");
case 4,5:
//Line3
System.out.println("Four and Five");
break;
default:
System.out.println("Default");

Ans: Compilation error in Line 3 as multiple values are not allowed in case

5. Which of the following is correct usage of a relational operator made in if statement.

Ans : if (firstName.equals(“Annie”)&&salary==50000)
6. Identify the output of the below code:

public class TestDemo {


public static void main(String[] args){
boolean a = true;
boolean b = true;
boolean c = false;
boolean d = true;
System.out.println(a&&b||c&&d);
}

Ans – true

7.

public class UtilTest {


@Rule
public ExpectedException thrown = ExpectedException.none();
//@Test(expected = Exception.class)
//Line1
@Test
public void test1() throws Exception{
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}

Ans - @Test

8. Which of the following component is responsible to compile, debug a java


program?

Ans-JDK

9. What is the output for the below code?

interface Fruits{
public void printPrice();
}
public class Apple {
public static void main(String[] args){
Fruits fruits = new Fruits(){
public void printPrice(){
System.out.println("150");
}

};
fruits.printPrice();
}
}

Ans-150

10. Which among the following is valid option for wildcards?(select 2 options)

A. Used to relax restriction on the variable


B. Used in scenario where type being operated upon is not known
C. Used in generic method type argument
D. Can access members of super class

Ans:

A. Used to relax restriction on the variable


B. Used in scenario where type being operated upon is not known

11. Which of the below method name is valid as per Java naming convention?

Ans: methodName

12. Consider the Junit test class with junit fixture annotations and the methods
as below:
@BeforeClass ---- init()
@AfterClass ---- close()
@Before ---- setUp()
@After ---- tearDown()
@Test----testSum1()
@Test----testEven1()
In which order the methods will execute?

Ans – init() setup() testSum() tearDown() setUp() testEven() tearDown() close()

13. Which of the following is the correct syntax to declare the abstract method evaluate?

14. Predict the output of the below code.


class Car{
void start(){
System.out.println("Car Starts");
}
}
class Bike{
void start(){
System.out.println("Bike Starts");
}
}
class Automobile extends Car{
void start(){
System.out.println("Automobile Starts");
}
}
public class ExceptionDemo {
public static void main(String[] args){
System.out.println("Implementing Typecasting");
Car d = new Car();
Automobile automobile = (Automobile) d;
automobile.start();
}

Ans :

Displays "Implementing type casting" and RUNTIME EXCEPTION java.lang.ClassCastException

15. Analyze the below code and predict the outcome when compiled and executed?

public class Demo extends Book {


int bookid =4567;

public int getValue() {


return bookid;
}

public void call() {


System.out.println(super.getValue());//Line 1
}

public static void main(String args[]){

Book book = new Book();


super.call();//Line 2

}
}

public class Book {


int bookId = 17897;
public int getValue(){
return bookId;
}

Ans – Compilation error in Line2 as super keyword cannot be used in static context

16. Which of the following condition will not allow the finally block to be executed?

Ans – when System.exit(1) is called

17. What is the result of the following?

public class TestDemo {


public static void main(String[] args){
try{
throw new ArithmeticException("AE");
}catch(ArithmeticException e2){
System.out.println(e2.getClass());
}catch(Exception e1){
System.out.println("E1");
}
}
}

Ans - class java.lang.ArithmeticException

18. What is the result of attempting to compile and run this program?

class CustomException extends Exception{}


class Customer extends CustomException{}

public class ExceptionDemo1 {


public static void main(String[] args){
try{
throw new Customer();
}catch (CustomException customException){
System.out.println("Custom Exception Catch block");
}catch(Customer customer){
System.out.println("Customer catch block");
}
}

}
Ans – Compilation error because customer class exception is not throwable

19. Which of this statement is not correct and will lead to compilation error…………………….

20. What will be the output of the following code when executed?
public class DateTimeTester {
public static void main(String[] args){
LocalDateTime localDateTime = LocalDateTime.of(2020,5, 13, 20, 46);
System.out.println(localDateTime.get(ChronoField.HOUR_OF_DAY)
+localDateTime.getDayOfMonth());
}

Ans – 33

21. Which of the below code is implemented without best practices standard?

1. String[] str=new String[]{"Hi","Hello","Welcome"};


List strList=Arrays.asList(str);
for(iterator itr=strList.iterator();itr.hasNext();){
System.out.println(itr.next);

2. Integer i1=new Integer(11);


Integer i2=new Integer(11);
System.out.println(i1==i2);

Ans: Option 1 doesnot follow best practices. Can be improved using for(String s:str)

22. Which of the following is used for the automatic accurate tracking for the decimal values:

Ans:BigDecimal
23. Given:
public class TestDemo1 {
public static void main(String[] args)
{
int i=4;
int j=4;
System.out.println(i==j);
Integer w1=new Integer(4);
Integer w2=new Integer(4);
System.out.println(w1==w2);
}
}
Ans: no issues in the above code

24. Consider the following statements:

1.

You might also like