 Company-Specific Courses
Free Resources Edit Edit

# InfyTQ Questions and Answers | Java Qualifying Round

Published on 24 Mar 2021

In this article, we will be discussing some of the InfyTQ Java questions asked in the InfyTQ sample test released officially by Infosys. These InfyTQ sample questions will give you a fair idea about the difficulty level of the Infytq exam.

Have you registered for the Infosys InfyTQ certification exam? If you haven’t, here’s your chance.

Check out InfyTQ Final Round Python Coding Questions here Question 1:

An Employee Management System application is used to maintain information about employees in an organization. In the application, employee details are stored in the ascending order of the employee Ids. Which algorithmic design technique would best fit if an employee needs to be searched based on the employee ld.

A. Greedy Approach

B. Brute Force

C. Divide and Conquer

D. Dynamic Programming

Explanation:

Greedy algorithms are very fast. A lot faster than the two other alternatives (Divide & Conquer, and Dynamic Programming). They're used because they're fast. Most of the popular algorithms using Greedy have shown that Greedy gives the global optimal solution every time. Some of these include:

• Dijkstra's Algorithm
• Kruskal's algorithm
• Prim's algorithm
• Huffman trees

Question 2:

What is the output of the following code snippet?

public class Tester {
Public static void main (String[ ] args) {
for(int loop = 0;loop < 5;loop++) {
if(loop > 2) {
continue;
}
if(loop>4) {
break;
}
System.out.println(loop) ;
}
}
}


A:

0

1

2

B:

0

C:

0

1

2

3

4

D:

0

1

Explanation:

0th iteration:

loop<5 //True

loop>2→ Continue //False

loop>4→ Break //False

Print→ 0

1st iteration:

loop<5 //True

loop>2→ Continue //False

loop>4→ Break //False

Print→ 1

2nd iteration:

loop<5 //True

loop>2→ Continue //False

loop>4→ Break //False

Print→ 2

3rd iteration:

loop<5 //True

loop>2→ Continue //True

loop>4→ Break //no execution

Print→ //Nothing

4th iteration:

loop<5 //True

loop>2→ Continue //True

loop>4→ Break //no execution

Print→ //Nothing

Question 3:

Which of the following statements is TRUE with respect to Java language being platform independent?

A. The code in the java file is platform dependent

B. The JVM is the same across all operating systems

C. A java program written in a machine with Windows operating system cannot be executed on a machine having Linux operating system though Java is installed accordingly

D. A .class file can be run in any operating system where Java is installed

Explanation:

A. Java is a class-based and object-oriented programming language. It is a platform-independent language i.e. the compiled code can be run on any java supporting platform. It runs on the logic of “Write once, run anywhere”.

B. JVM makes java portable (write once, run anywhere). Each operating system has a different JVM, however, the output they produce after execution of byte code is the same across all operating systems.

C. The whole point of Java being platform-independent is for it to run in any operating system.

D. This is the only statement true.

Question 4:

What is the output of the following code snippet?

class Demo{
public static int specialAdd(int num1) {
if (num1!=0)
else
return 3;
}
public static int extraordinaryAdd(int num2) {
if (num2!=0)
else
return 0;
}
public static void main (String [ ] args) {
}
}


A. 80

B. 52

C.70

D. 25

Explanation: From this, we come to know that Therefore 28+52 = 80

Question 5:

What is the output of the code given below when run with the default Junit runner?

class Computation {
public int add(int num1, int num2) {
return num1 + num2 ;
}
public int divide(int num1, int num2) {
return num1 / num2 ;
}
}
public class TestComputation {
Computation comput = new Computation ( ) ;
@Test
public void testAdd1 ( ) {
int expected = 5 ;
int actual = comput.add(2, 3) ;
Assert.assertEquals(expected, actual) ;
}
@Test
public void testAdd2 ( ) {
int expected = 7 ;
int actual = comput.add(2, 5) ;
Assert.assertEquals(expected , actual) ;
}
}


Explanation:

Both would pass as expected and the actual values match in both

Question 6:

Consider the code snippet given below:

class Customer {
public int custId ;
public String custName ;
}
public class Tester {
public static void main (String args{ } ) {
Customer obj = new Customer ( ) ;
Customer objOne = new Customer ( ) ;
Customer objTwo ;
Customer objThree = obj ;
}
}


A. 3 objects and 1 reference variable

B. 2 objects and 4 reference variables

C. 4 objects and 4 reference variables

D. 2 objects and 3 reference variables

Explanation:

We know that an object is created by using a new keyword in java, a new keyword is used 2 times in the above code and hence 2 objects are created.

There are 4 references created in the above code namely→ obj, objOne, objTwo, objThree

Question 7:

Consider the code given below:

class Student {
private int studentId ;
private String studentName ;
Student (int studentId,String studentName) {
this.studentId = studentId ;
this.studentName = studentName ;
}
}
class College {
private Student studentId ;
private int basicFees ;
College (Student studentId, int basicFees) {
this.studentId = student ;
this.basicFees = basicFees ;
}
}


Identify the relationship between Student and College classes.

A. Aggregation

B. Association

C. Inheritance

D. The two classes are not related

Explanation:

Association is a semantically weak relationship (a semantic dependency) between otherwise unrelated objects. An association is a “using” relationship between two or more objects in which the objects have their own life and there is no owner.

An aggregation is a specialized form of association between two or more objects in which each object has its own life cycle but there exists ownership as well. Aggregation is a typical whole/part or parent/child relationship but it may or may not denote physical containment. An essential property of an aggregation relationship is that the whole or parent (i.e. the owner) can exist without the part or child and vice versa.

This code is an example of aggregation where class Student can exist without class College but not the other way around.

Question 8:

What is the output of the following code snippet?

public class ExceptionExample {
public void checkForExceptions(int num1, int num2) {
int intArr [ ] = {1,2,3} ;
String str = null ;
System.out.println("Before any exception!") ;
try{
str.charAt(0) ;
System.out.println(num1 / num1) ;
System.out.println("Enjoy no exception!") ;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException handler!") ;
} catch (NullPointerException e) {
System.out.println("NullPointException handler!") ;
} catch (Exception e) {

System.out.println("Default exception handler!") ;
} finally {
System.out.println("In finally!");
}
System.out.println("After handling exception!") ;
}
public static void main(String [ ] args)
{
ExceptionExample exceptionExample = new ExceptionExample( ) ;
try {
exceptionExample.checkForExceptions(2, 0) ;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException handler in main!") ;
}
System.out.println("End of main") ;
}
}


A:

Before any exception!

Enjoy no exception!

In finally!

After handling exception!

End of main

B:

Before any exception!

Default exception handler!

In finally!

After handling exception!

End of main

C:

Before any exception!

ArithmeticException handler!

In finally!

After handling exception!

ArithmeticException handler in main!

End of main

D:

Before any exception!

NullPointerException handler!

In finally!

After handling exception!

End of main

Explanation:

So in this code, the execution starts from the driver code which has→ exceptionExample.checkForExceptions(2, 0) ; here the arguments are passed to the method checkForExceptions() which is present in the class. Before it starts the operation it prints “Before any exception” after which it executes str.charAt(0) ; this would throw an error as the str has been initialized with NULL. This exception would be caught and the statement would be printed accordingly as “NullPointException handler!”. As there are no further executions in the method checkForExceptions() control will return to the finally block, where “In finally!” will be printed. The final statement in the method “After handling exception!” will also be printed. The control returns to the river code and the last line will be executed, that is to print “End of main”.

Question 9:

Consider the problem size as ‘n’. Find the worst-case time complexity of the following algorithm.

if num1>num2 then
for (couter1=1;counter1<=n;counter1=counter1*2)
print(“num1 is greater than num2”)
end-for
else
for(counter2=1;counter2<=n;counter2=counter2+1) {
print(“num2 is greater than num1”)
end-for
end-if


A. O(n)

B. O(n2)

C. O(log n)

D. O(n log n)

Explanation:

Time complexity of for (couter1=1;counter1<=n;counter1=counter1*2) would be O(log n)

Time complexity of for(counter2=1;counter2<=n;counter2=counter2+1) would be

O(n)

So the time complexity would be O(n log n)

Question 10:

Consider the code given below which is written in the file ‘Demo.java’.

class Book{
/ /Class definition
}
class Demo{
public static void main(String [ ] args) {
}
}


How many .class files will be generated for the above code and which class out of the two, Demo or Book, will be loaded into the main memory first when executed?

A. 2, Demo

B. 2, Book

C. 1, Demo

D. 1, Book

Explanation:

There are 2 classes here, class Book and class Demo, hence there will be 2 .class files created while the program gets compiled. Execution always starts from the class which has the main method, hence class Demo would be loaded first into the main memory.

Question 11:

Consider the Binary Search code given below:

public static int search(int arrayOfElements [ ], int low, int high, int elementToBeSearched) {
if (low <= high) {
int mid = (low + high) / 2 ;
if (arrayOfElements[mid] == elementToBeSearched)
return mid;
if (arrayOfElements[mid] < elementToBeSearched)
return seach(arrayOfElements, mid + 1, high, elementToBeSearched) ;
return search (arrayOfElements, low, mid -1, elementToBeSearched);
}
return -1;
}


Consider the arrayOfElements having 6 elements with low as 0 and high as 5. The elements of the array are as follows.

5 6 9 12 15 29

Find the number of iterations when using binary search if the elementToBeSearched is 6?

A. 1

B. 2

C. 3

D. 4

Explanation:

1st iteration: low= 0

high= 5

mid= (0+5)/2 = 2

a>key, which means 9>6

2nd iteration: low = 0

high = mid-1 = 1

mid = (0+1)/2 = 0

a<key, which means 5<6

3rd iteration: low = mid+1 = 0+1 = 1

high = 1

mid = (1+1)/2 = 1

a==key, which means 6==6.

Question 12:

Consider the code given below.

class Item{

public String itemId;

String itemName ;

protected float itemPrice;

private int itemDiscount ;

public Item(String itemId,String itemName)

this.itemId=this.itemId;

this.itemName=itemName;

}

}

Identify the access specifier of the data member ‘itemName’.

A. public

B. protected

C. private

D. default

Explanation:

When we don't use any keyword explicitly, Java will set default access to a given class, method, or property. The default access modifier is also called package-private, which means that all members are visible within the same package but aren't accessible from other packages

Question 13:

What is the output of the following code snippet?

public class Question {
public static void main (String [ ] args) {
int var = 22, anotherVar = 7, result ;
String str = “One” ;
String anotherStr = “Two” ;
result = var*anotherVar / anotherVar ;
if ( result < 22 ) {
System.out.println(str) ;
}
else {
System.out.println(anotherStr) ;
}
}
}


A. Compilation error: incorrect use of operators

B. One

C. No output is displayed

D. Two

Explanation:

Here the main equation to be concentrated is → result = var*anotherVar / anotherVar ; var has the value 22 in it and anotherVar has the value 7 so the equation can be written as 24*7/7, but because of BODMAS 7/7 will be executed first which will result in 1 and this will be considered for multiplication as 22*1 which gives us 22. So the final value which is stored in the variable result is 22. While checking if condition 22>22 will be a False and hence anotherStr which has the value “Two” will be printed as the output.

Question 14:

What is the output of the following code snippet?

class Bill {
int itemPrice
public Bill (int itemPrice) {
this.itemPrice = itemPrice ;
}
void display ( ) {
int itemPrice = 20 ;
System.out.println (itemPrice) ;
}
}
class Demo {
public static void main(String [ ] args) {
Bill billobj = new Bill (10) ;
System.out.println(billobj.itemPrice) ;
billobj.display ( ) ;
}
}


A:

10

0

B:

10

20

C:

10

10

D:

Error in the class as there is no default constructor defined

Explanation:

Here there are 2 printing statements one given directly in the driver code which is →  System.out.println(billobj.itemPrice) ;

And the other one inside the function display which is→

System.out.println (itemPrice) ;

The 1st printing statement, prints the itemPrice which is passed as a parameter via the constructor during the object creation. So value 10 will be printed.

The 2nd printing statement, prints the itemPrice which is initialized inside the display function itself. So the value printed will be 20.

Question 15:

Consider the below code:

public class Tester {
public static void main (String [ ] args) {
int [ ] tempList = { 1, -1, -2 } ;
int [ ] numList = {-2, -1, 1 } ;
int length = numList.length ;
for (int value : tempList) {
int tempValue = value ;
if (value<0) {
tempValue = length - Maths.abs(value) ;
}
if(value == tempList [tempValue]) {
if(value<0) {
numList [length-tempValue]=value ;

}
else {
numList [tempValue]=value ;
}
}
else {
numList  = value ;
}
}
}
}


What will be the elements of numList after the execution of the above code?

A. [-2,-1,1]

B. [-2,-2,1]

C. [1,-2,1]

D. [-2,-1,2]

Explanation:

Values are going to be the same after the 3rd iteration of for loop.

Question 16:

What will be the output of the below code:

class ListExample
{
public static void main ( String [ ] args)
{
List<String> list = new ArrayList<>( ) ;
Iterator<Object> iter = list.iterator ( ) ;
while (iter.hasNext ( ) )
System.out.print ( iter.next ( ) .toString ( ) + “ “) ;
System.out.println ( ) ;
}
}


Assumption: All classes, interfaces, and necessary methods are available

A. I Love Java Language

B. Error: Incompatible types: String cannot be converted to Object

C. Error: Iterator cannot be created for Object

D. Error: toString() cannot be applied on a String object

Explanation:

We are creating a list reference and inside the list reference, we are assigning the objects of Arraylist. This can be done as Arraylist is a child of List interface. We have added multiple strings inside the list which is also fine. Iterator<Object> iter = list.iterator ( ) ; this line would throw an error as the list is for strings and we are assigning it to the Iterator<Object>. The error is basically an incompatible type.

Question 17:

What is the output of the following code?

class Base {
private int fun ( ) {
return 0;
}
public int run ( ) {
return 3;
}
}
class Derived extends Base [
private int fun ( ) {
return 1 ;
}
public int run ( ) {
return fun ( ) ;
}
}
class Derived1 extends Derived {
public int fun ( ) {
return 2 ;
}
}
class Tester {
public static void main ( String [ ] args) {
Base baseRef = new Derived1 ( ) ;
System.out.println(baseRef.run ( ) )
}
}


A. 1

B. 2

C. 0

D. 3

Explanation:

In the above-given code, all the reference is created for Base class but it is holding the object of Derived1 class. And in Java, all classes are nonstatic by default. Hence the higher preference will be given to the object. Therefore baseRef.run() will go in search of a function run() in Derived1 class. But the derived1 class doesn't have any method run. Therefore the control will be taken to the parent class of Derived1 class which is the Derived class. In the Derived class, we have a run method that shifts the control to the fun method which in turn returns a 1 as the value for the printing.

Question 18:

Consider an input queue inQueue of Strings with the following elements:

inQueue(Front->Rear):”Crib”, “Bat”, “Crab”, “Carl”, “Cat”, “Row”

What will be the output of the below function if the above inQueue and the String “Par” are passed as input parameters?

public static ArrayDeque<String> compareStrings(Queue inQueue, String inString) {
ArrayDeque<String> outStack=new ArrayDeque<String>(6) ;
String tempString=”Empty” ;
while ( ! ( inQueue.isEmpty ( ) ) {
if ( ! inQueue.dequeue ( ).length ( ) ==inString.length ( ) ) ) {
outStack.push(inQueue.dequeue ( ) );
}
else {
tempString=inQueue.dequeue ( ) ;
outStack.pop ( ) ;
}

}
outStack.push(tempString) ;
return outStack;
}


Assumptions:

•Queue class, with the necessary methods, is available

•ArrayDeque class, with the necessary methods, is available

A. outStack(Top->Bottom): [Empty]

B. outStack(Top->Bottom): [Empty, Bat]

C. outStack(Top->Bottom): [Row, Bat]

D. outStack(Top->Bottom): [Row]

Question 19:

Consider the below code:

class ClassA
{
void firstMethod()
{
System.out.println("Johnny Johnny . . . ,");
}
void secondMethod()
{
System.out.println("Yes Papa.");
}
void thirdMethod()
{
System.out.println("Eating Sugar . . . ,");
}
}
class ClassB extends ClassA
{
void secondMethod()
{
super.firstMethod();
super.secondMethod();
super.thirdMethod();
System.out.println("No Papa.");
}
void thirdMethod()
{
System.out.println("Telling Lies . . . ,");
}
}

class ClassC extends ClassB
{
void firstMethod()
{
System.out.println("Open your mouth . . . , Ha . Ha . Ha .");
}
void secondMethod()
{
System.out.println("No Papa.");
}
void thirdMethod()
{
super.secondMethod();
super.thirdMethod();
this.secondMethod();
}
public static void main (String[] args)
{
ClassA objA = new ClassA();
ClassB objB = new ClassB();
ClassC objC = new ClassC();
//Line1
}
}



Which among the below options if written at //Line 1, prints the rhyme correctly?

Choose two Correct options.

The expected output for your reference:

Johnny Johnny . . . ,

Yes Papa .

Eating Sugar . . . ,

No Papa .

Telling Lies . . . ,

No Papa .

Open your mouth . . . , Ha . Ha . Ha .

A:

objA.firstMethod();

objA.secondMethod();

objA.thirdMethod();

objC.firstMethod();

B:

objC.thirdMethod();

objC.firstMethod();

C:

objB.secondMethod();

objB.thirdMethod();

objC.secondMethod();

objC.firstMethod();

D:

objA.firstMethod();

objB.secondMethod();

objC.thirdMethod();

objC.firstMethod();

Explanation:

A. Would skip the line “No Papa.” both times.

B. Would print the correct answer

C. Would print the correct answer

D. The lines would be random with multiple repetitions of the lines from the rhyme

Question 20:

Consider the code given below:

Identify the code that needs to be filled in Line 1, 2, and 3 respectively such that:

•the student id is auto-generated starting from 501 in steps of 1

•the method ‘getNoOfStudent’ returns the total number of students enrolled at any given point.

class Student {
private int studentId ;
private String studentName ;
private int yearOfEnrollment ;
public static int counter ;
static {
/ / Line 1
}
public Student ( String name, int yearOfEnrollment) {
this.studentName=name ;
this.yearOfEnrollment=yearOfEnrollment ;
/ / Line 2
}
public static int getNoOfStudent ( ) {
/ / Line 3
}
}


A:

Line 1: Student.counter=501;

Line 2: this.studentId=Student.counter++;

Line 3: return (Student.counter-500);

B:

Line 1: Student.counter=501;

Line 2: this.studentId=++Student.counter;

Line 3: return (Student.counter-501);

C:

Line 1: Student.counter=500;

Line 2: this.studentId=Student.counter++;

Line 3: return (Student.counter-500);

D:

Line 1: Student.counter=500;

Line 2: this.studentId=++Student.counter;

Line 3: return (Student.counter-500);

Explanation:

The counter has to start from 501, so options C and D get eliminated as their counter starts with 500.

To know how many students have enrolled we would have to subtract 500 from the final count, that is for example if there are 10 students the final enrolment would be 510, now to find the total number of students, we would have to perform 510-500 = 10. But if we perform 510-501 it would give us 9 which is not the actual count.

Did you know that Infosys will be conducting their coding contest, i.e HackWithInfy for the 2022 batch? To read all about it click here.

## Suggested Articles:

InfyTQ Questions and Answers | Python Qualifying Round

InfyTQ 2022 batch | Infosys InfyTQ Registration & Process

HackWithInfy 2021 | Infosys Coding Contest for 2022 batch

InfyTQ Questions and Answers | InfyTQ Aptitude for Qualifying Round

InfyTQ Questions and Answers | Java Qualifying Round

InfyTQ Final Round Python Coding Questions

InfyTQ Questions | InfyTQ Final Round DBMS Questions

InfyTQ Questions | Python MCQs | Final Round

InfyTQ Questions | InfyTQ Final Round Java MCQs  