Infytq Java Solve

Q. Which of the following statements is TRUE with respect to JAVA Language being platform independent?

a) The code in Java file is platform independent
b) A Java program written in a machine with windows operating system cannot be executed on a machine having other OS
c) A class file can be run in any operating system where Java is installed
d) The Jvm is the same across all operating systems

Answer: c) A class file can be run in any operating system where Java is installed


Q. Consider the code given below:

public int search(int arrayOfElements[], int elementToBeSearched) {
	for(int index=0; index<arrayOfElements.length; index++) {
		//Returning the index of the element if the element is found
		if(arrayOfElements[index] == elementToBeSearched)
			return index;
	}
	return -1;
}

Identify the algorithmic design technique used.

a) Dynamic Programming
b) Divide and Conquer
c) Brute Force
d) Greedy Approach

Answer: c) Brute Force

Explanation: In this case we are checking all the possible position to get the search element so it is a brute force approach.


Q. What will be the output of the following Java code?

class access
    {
        public int x;
 	private int y;
        void cal(int a, int b)
        {
            x =  a + 1;
            y =  b;
        }
    }
    public class access_specifier
    {
        public static void main(String args[])
        {
            access obj = new access();
            obj.cal(2, 3);
            System.out.println(obj.x + " " + obj.y);
        }
   }

a) 3 3
b) 2 3
c) Runtime Error
d) Compilation Error

Answer: c) Runtime Error

Explanation: None.
Output:
$ javac access_specifier.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The field access.y is not visible


What will be the output of the following Java code?

class static_out
    {
        static int x;
 	static int y;
        void add(int a, int b)
        {
            x = a + b;
            y = x + b;
        }
    }
    public class static_use
    {
        public static void main(String args[])
        {
            static_out obj1 = new static_out();
            static_out obj2 = new static_out();
            int a = 2;
            obj1.add(a, a + 1);
            obj2.add(5, a);
            System.out.println(obj1.x + " " + obj2.y);
        }
   }

a) 7 7.4
b) 6 6.4
c) 7 9
d) 9 7

Answer: c) 7 9

Explanation: None.
Output:
$ javac static_use.java
$ java static_use
7 9


Q. 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

Answer: a)
0
1
2

Explanation: 

1. 0th iteration:

loop<5 //True
loop>2→ Continue //False
loop>4→ Break //False

Print→ 0

2. 1st iteration:

loop<5 //True
loop>2→ Continue //False
loop>4→ Break //False

Print→ 1

3. 2nd iteration:

loop<5 //True
loop>2→ Continue //False
loop>4→ Break //False

Print→ 2

4. 3rd iteration:

loop<5 //True
loop>2→ Continue //True
loop>4→ Break //no execution

Print→ //Nothing

5. 4th iteration:

loop<5 //True
loop>2→ Continue //True loop>4→ Break //no execution
Print→ //Nothing


Q. What will be the output for the following code

class Demo{
    public static int specialAdd(int num1) {
        if (num1!=0)
            return (num1+2)+specialAdd(num1-1) ;
        else
            return 3;
    }
    public static int extraordinaryAdd(int num2) {
            if (num2!=0)
                return specialAdd(num2)+extraordinaryAdd(num2-1) ;
            else
                return 0;
    }
    public static void main (String [ ] args) {
            System.out.println( (extraordinaryAdd(5) ) ) ;
    }
}  

a) 80
b) 52
c) 70
d) 25

Answer: a) 80

Q. 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) ;
    }
}      

a) Both testAdd1 and testAdd2 fail
b) testAdd1 fails and testAdd2 passes
c) Both testAdd1 and testAdd2 pass
d) testAdd1 passes and testAdd2 fails

Answer: c) Both testAdd1 and testAdd2 pass

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


Q. 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

Answer: b) 2 objects and 4 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 


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

Answer: a)Aggregation

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.


Q. 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

c)
Before any exception!
ArithmeticException handler!
In finally!
After handling exception!
ArithmeticException handler in main!
End of main

b)
Before any exception!
Default exception handler!
In finally!
After handling exception!
End of main

d)
Before any exception!
NullPointerException handler!
In finally!
After handling exception!
End of main

Answer: 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”.


Q. 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) 

Answer: 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)


Q. 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

Answer: a) 2, Demo

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.


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

Answer: c) 3

Explanation:

1. 1st iteration:
low= 0
high= 5
mid= (0+5)/2 = 2
a[2]>key, which means 9>6

2. 2nd iteration:
low = 0
high = mid-1 = 1 
mid = (0+1)/2 = 0
a[0]<key, which means 5<6

3. 3rd iteration:
low = mid+1 = 0+1 = 1
high = 1
mid = (1+1)/2 = 1
a[1]==key, which means 6==6.


Q. 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

Answer: 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

Leave a Comment

Your email address will not be published. Required fields are marked *