250+ TOP MCQs on Generic Methods and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) on “Generic Methods”.

1. What are generic methods?
a) Generic methods are the methods defined in a generic class
b) Generic methods are the methods that extend generic class methods
c) Generic methods are methods that introduce their own type parameters
d) Generic methods are methods that take void parameters

Answer: c
Clarification: Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

2. Which of these type parameters is used for a generic methods to return and accept any type of object?
a) K
b) N
c) T
d) V

Answer: c
Clarification: T is used for type, A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

3. Which of these type parameters is used for a generic methods to return and accept a number?
a) K
b) N
c) T
d) V

Answer: b
Clarification: N is used for Number.

4. Which of these is an correct way of defining generic method?
a) name(T1, T2, …, Tn) { /* … */ }
b) public name { /* … */ }
c) class name[T1, T2, …, Tn] { /* … */ }
d) name{T1, T2, …, Tn} { /* … */ }

Answer: b
Clarification: The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method’s return type. For static generic methods, the type parameter section must appear before the method’s return type.

5. Which of the following allows us to call generic methods as a normal method?
a) Type Interface
b) Interface
c) Inner class
d) All of the mentioned

Answer: a
Clarification: Type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets.

6. What will be the output of the following Java program?

  1.     import java.util.*;
  2.     public class genericstack <E>
  3.     {
  4.         Stack <E> stk = new Stack <E>();
  5. 	public void push(E obj) 
  6.         {
  7.             stk.push(obj);
  8. 	}
  9. 	public E pop() 
  10.         {
  11.             E obj = stk.pop();
  12. 	    return obj;
  13. 	}
  14.     }
  15.     class Output
  16.     {
  17.         public static void main(String args[])
  18.         {
  19.             genericstack <String> gs = new genericstack<String>();
  20.             gs.push("Hello");
  21.             System.out.println(gs.pop());
  22.         }
  23.     }

a) H
b) Hello
c) Runtime Error
d) Compilation Error

Answer: b
Clarification: None.
Output:

$ javac Output.javac
$ java Output
Hello

7. What will be the output of the following Java program?

  1.     import java.util.*;
  2.     public class genericstack <E>
  3.     {
  4.         Stack <E> stk = new Stack <E>();
  5. 	public void push(E obj)
  6.         {
  7.             stk.push(obj);
  8. 	}
  9.         public E pop()
  10.         {
  11.             E obj = stk.pop();
  12. 	    return obj;
  13. 	}
  14.     }
  15.     class Output
  16.     {
  17.         public static void main(String args[])
  18.         {
  19.             genericstack <Integer> gs = new genericstack<Integer>();
  20.             gs.push(36);
  21.             System.out.println(gs.pop());
  22.         }
  23.     }

a) 0
b) 36
c) Runtime Error
d) Compilation Error

Answer: b
Clarification: None.
Output:

$ javac Output.javac
$ java Output
36

8. What will be the output of the following Java program?

  1.     import java.util.*;
  2.     public class genericstack <E>
  3.     {
  4.         Stack <E> stk = new Stack <E>();
  5.         public void push(E obj)
  6.         {
  7.             stk.push(obj);
  8. 	}
  9. 	public E pop()
  10.         {
  11.             E obj = stk.pop();
  12. 	    return obj;
  13. 	}
  14.     }
  15.     class Output 
  16.     {
  17.         public static void main(String args[]) 
  18.         {
  19.             genericstack <String> gs = new genericstack<String>();
  20.             gs.push("Hello");
  21.             System.out.print(gs.pop() + " ");
  22.             genericstack <Integer> gs = new genericstack<Integer>();
  23.             gs.push(36);
  24.             System.out.println(gs.pop());
  25.         }
  26.     }

a) Error
b) Hello
c) 36
d) Hello 36

Answer: d
Clarification: None.
Output:

$ javac Output.javac
$ java Output
Hello 36

Advanced 250+ TOP MCQs on Annotations and Answers

This set of Advanced Java Multiple Choice Questions & Answers (MCQs) on “Annotations”.

1. Which version of Java introduced annotation?
a) Java 5
b) Java 6
c) Java 7
d) Java 8

Answer: a
Clarification: Annotation were introduced with Java 5 version.

2. Annotation type definition looks similar to which of the following?
a) Method
b) Class
c) Interface
d) Field

Answer: c
Clarification: Annotation type definition is similar to an interface definition in which the keyword interface is preceded by the sign @.

3. Which of the following is not pre defined annotation in Java?
a) @Deprecated
b) @Overriden
c) @SafeVarags
d) @FunctionInterface

Answer: b
Clarification: @Overriden is not a pre defined annotation in Java. @Depricated, @Override, @SuppressWarnings, @SafeVarags and @FunctionInterface are the pre defined annotations.

4. Annotations which are applied to other annotations are called meta annotations.
a) True
b) False

Answer: a
Clarification: Annotations which are applied to other annotations are called meta annotations.

5. Which one of the following annotations is not used in Hibernate?
a) @Entity
b) @Column
c) @Basic
d) @Query

Answer: d
Clarification: @Query is not an annotation used in Hibernate.

6. Which one of the following is not ID generating strategy using @GeneratedValue annotation?
a) Auto
b) Manual
c) Identity
d) Sequence

Answer: b
Clarification: Auto, Table, Identity and Sequence are the ID generating strategies using @GeneratedValue annotation.

7. Which one of the following is not an annotation used by Junit with Junit4?
a) @Test
b) @BeforeClass
c) @AfterClass
d) @Ignored

Answer: d
Clarification: @Test, @Before, @BeforeClass, @After, @AfterClass and @Ignores are the annotations used by Junit with Junit4.

8. Using which annotation non visible or private method can be tested?
a) @VisibleForTesting
b) @NonVisibleForTesting
c) @Visible
d) @NonVisible

Answer: a
Clarification: Using @VisibleForTesting annotation private or non visible method can be tested.

9. Which of the following annotation is used to avoid execution of Junits?
a) @NoTest
b) @explicit
c) @avoid
d) @ignore

Answer: d
Clarification: @ignore annotation is used to avoid execution of Junits.

10. Which is the Parent class of annotation class?
a) Class
b) Object
c) Main
d) Super

Answer: b
Clarification: Object is the parent class of annotation class.

250+ TOP MCQs on Arrays and Answers

Java MCQs on Array Data Structure of Java Programming Language.

1. Which of these operators is used to allocate memory to array variable in Java?
a) malloc
b) alloc
c) new
d) new malloc

Answer: c
Clarification: Operator new allocates a block of memory specified by the size of an array, and gives the reference of memory allocated to the array variable.

2. Which of these is an incorrect array declaration?
a) int arr[] = new int[5]
b) int [] arr = new int[5]
c) int arr[] = new int[5]
d) int arr[] = int [5] new

Answer: d
Clarification: Operator new must be succeeded by array type and array size.

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

    int arr[] = new int [5];
    System.out.print(arr);

a) 0
b) value stored in arr[0]
c) 00000
d) Class [email protected] hashcode in hexadecimal form

Answer: d
Clarification: If we trying to print any reference variable internally, toString() will be called which is implemented to return the String in following form:
[email protected] in hexadecimal form

4. Which of these is an incorrect Statement?
a) It is necessary to use new operator to initialize an array
b) Array can be initialized using comma separated expressions surrounded by curly braces
c) Array can be initialized when they are declared
d) None of the mentioned

Answer: a
Clarification: Array can be initialized using both new and comma separated expressions surrounded by curly braces example : int arr[5] = new int[5]; and int arr[] = { 0, 1, 2, 3, 4};

5. Which of these is necessary to specify at time of array initialization?
a) Row
b) Column
c) Both Row and Column
d) None of the mentioned

Answer: a
Clarification: None.

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

  1.     class array_output 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             int array_variable [] = new int[10];
  6. 	    for (int i = 0; i < 10; ++i) 
  7.             {
  8.                 array_variable[i] = i;
  9.                 System.out.print(array_variable[i] + " ");
  10.                 i++;
  11.             }
  12.         } 
  13.     }

a) 0 2 4 6 8
b) 1 3 5 7 9
c) 0 1 2 3 4 5 6 7 8 9
d) 1 2 3 4 5 6 7 8 9 10

Answer: a
Clarification: When an array is declared using new operator then all of its elements are initialized to 0 automatically. for loop body is executed 5 times as whenever controls comes in the loop i value is incremented twice, first by i++ in body of loop then by ++i in increment condition of for loop.
output:

$ javac array_output.java
$ java array_output
0 2 4 6 8

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

  1.     class multidimention_array 
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.             int arr[][] = new int[3][];
  6.             arr[0] = new int[1];
  7.             arr[1] = new int[2];
  8.             arr[2] = new int[3];               
  9. 	    int sum = 0;
  10. 	    for (int i = 0; i < 3; ++i) 
  11. 	        for (int j = 0; j < i + 1; ++j)
  12.                     arr[i][j] = j + 1;
  13. 	    for (int i = 0; i < 3; ++i) 
  14. 	        for (int j = 0; j < i + 1; ++j)
  15.                     sum + = arr[i][j];
  16. 	    System.out.print(sum); 	
  17.         } 
  18.     }

a) 11
b) 10
c) 13
d) 14

Answer: b
Clarification: arr[][] is a 2D array, array has been allotted memory in parts. 1st row contains 1 element, 2nd row contains 2 elements and 3rd row contains 3 elements. each element of array is given i + j value in loop. sum contains addition of all the elements of the array.
output:

$ javac multidimention_array.java
$ java multidimention_array
10

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

  1.     class evaluate 
  2.     {
  3.         public static void main(String args[]) 
  4.             {
  5. 	        int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};
  6. 	        int n = 6;
  7.                 n = arr[arr[n] / 2];
  8. 	        System.out.println(arr[n] / 2);
  9.             } 
  10.     }

a) 3
b) 0
c) 6
d) 1

Answer: d
Clarification: Array arr contains 10 elements. n contains 6 thus in next line n is given value 3 printing arr[3]/2 i:e 3/2 = 1 because of int Value, by int values there is no rest. If this values would be float the result would be 1.5.
output:

$ javac evaluate.java
$ java evaluate
1

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

  1.     class array_output 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             char array_variable [] = new char[10];
  6. 	    for (int i = 0; i < 10; ++i) 
  7.             {
  8.                 array_variable[i] = 'i';
  9.                 System.out.print(array_variable[i] + "");
  10.             }
  11.         } 
  12.     }

a) 1 2 3 4 5 6 7 8 9 10
b) 0 1 2 3 4 5 6 7 8 9 10
c) i j k l m n o p q r
d) i i i i i i i i i i

Answer: d
Clarification: None.
output:

$ javac array_output.java
$ java array_output
i i i i i i i i i i

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

  1.     class array_output 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}};
  6.             int sum = 0;
  7.             for (int i = 0; i < 3; ++i)
  8.                 for (int j = 0; j <  3 ; ++j)
  9.                     sum = sum + array_variable[i][j];
  10.             System.out.print(sum / 5);
  11.         } 
  12.     }

a) 8
b) 9
c) 10
d) 11

Answer: b
Clarification: None.
output:

$ javac array_output.java
$ java array_output
9

250+ TOP MCQs on Access Control and Answers

Java Interview Questions and Answers on “Access Control”.

1. Which one of the following is not an access modifier?
a) Public
b) Private
c) Protected
d) Void

Answer: d
Clarification: Public, private, protected and default are the access modifiers.

2. All the variables of class should be ideally declared as?
a) private
b) public
c) protected
d) default

Answer: a
Clarification: The variables should be private and should be accessed with get and set methods.

3. Which of the following modifier means a particular variable cannot be accessed within the package?
a) private
b) public
c) protected
d) default

Answer: a
Clarification: Private variables are accessible only within the class.

4. How can a protected modifier be accessed?
a) accessible only within the class
b) accessible only within package
c) accessible within package and outside the package but through inheritance only
d) accessible by all

Answer: c
Clarification: The protected access modifier is accessible within package and outside the package but only through inheritance. The protected access modifier can be used with data member, method and constructor. It cannot be applied in the class.

5. What happens if constructor of class A is made private?
a) Any class can instantiate objects of class A
b) Objects of class A can be instantiated only within the class where it is declared
c) Inherited class can instantiate objects of class A
d) classes within the same package as class A can instantiate objects of class A

Answer: b
Clarification: If we make any class constructor private, we cannot create the instance of that class from outside the class.

6. All the variables of interface should be?
a) default and final
b) default and static
c) public, static and final
d) protect, static and final

Answer: c
Clarification: Variables of an interface are public, static and final by default because the interfaces cannot be instantiated, final ensures the value assigned cannot be changed with the implementing class and public for it to be accessible by all the implementing classes.

7. What is true of final class?
a) Final class cause compilation failure
b) Final class cannot be instantiated
c) Final class cause runtime failure
d) Final class cannot be inherited

Answer: d
Clarification: Final class cannot be inherited. This helps when we do not want classes to provide extension to these classes.

8. How many copies of static and class variables are created when 10 objects are created of a class?
a) 1, 10
b) 10, 10
c) 10, 1
d) 1, 1

Answer: a
Clarification: Only one copy of static variables are created when a class is loaded. Each object instantiated has its own copy of instance variables.

9. Can a class be declared with a protected modifier.
a) True
b) False

Answer: b
Clarification: Protected class member (method or variable) is like package-private (default visibility), except that it also can be accessed from subclasses. Since there is no such concept as ‘subpackage’ or ‘package-inheritance’ in Java, declaring class protected or package-private would be the same thing.

10. Which is the modifier when there is none mentioned explicitly?
a) protected
b) private
c) public
d) default

Answer: d
Clarification: Default is the access modifier when none is defined explicitly. It means the member (method or variable) can be accessed within the same package.

250+ TOP MCQs on StringBuffer Methods and Answers

Java MCQs on StringBuffer class’s methods of Java Programming Language.

1. Which of these methods of class StringBuffer is used to extract a substring from a String object?
a) substring()
b) Substring()
c) SubString()
d) None of the mentioned

Answer: a
Clarification: None.

2. What will s2 contain after following lines of Java code?

 StringBuffer s1 = "one";
StringBuffer s2 = s1.append("two")

a) one
b) two
c) onetwo
d) twoone

Answer: c
Clarification: Two strings can be concatenated by using append() method.

3. Which of this method of class StringBuffer is used to reverse sequence of characters?
a) reverse()
b) reverseall()
c) Reverse()
d) reverseAll()

Answer: a
Clarification: reverse() method reverses all characters. It returns the reversed object on which it was called.

4. Which of this method of class StringBuffer is used to get the length of the sequence of characters?
a) length()
b) capacity()
c) Length()
d) Capacity()

Answer: a
Clarification: length()- returns the length of String the StringBuffer would create whereas capacity() returns a total number of characters that can be supported before it is grown.

5. Which of the following are incorrect form of StringBuffer class constructor?
a) StringBuffer()
b) StringBuffer(int size)
c) StringBuffer(String str)
d) StringBuffer(int size , String str)

Answer: d
Clarification: None.

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.              StringBuffer c = new StringBuffer("Hello");
  6.              System.out.println(c.length());
  7.         }
  8.     }

a) 4
b) 5
c) 6
d) 7

Answer: b
Clarification: length() method is used to obtain length of StringBuffer object, length of “Hello” is 5.
Output:

$ javac output.java
$ java output
5

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

  1.   class output 
  2.   {  
  3.       public static void main(String args[]) 
  4.       {  
  5.           StringBuffer sb=new StringBuffer("Hello");  
  6.           sb.replace(1,3,"Java");  
  7.           System.out.println(sb);
  8.       }  
  9.   }

a) Hello java
b) Hellojava
c) HJavalo
d) Hjava

Answer: c
Clarification: The replace() method replaces the given string from the specified beginIndex and endIndex.

$ javac output.java
$ java output
HJavalo

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.            StringBuffer s1 = new StringBuffer("Hello");
  6.            s1.setCharAt(1,'x');
  7.            System.out.println(s1);
  8.         }
  9.     }

a) xello
b) xxxxx
c) Hxllo
d) Hexlo

Answer: c
Clarification: None.
Output:

$ javac output.java
$ java output
Hxllo

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.            StringBuffer s1 = new StringBuffer("Hello World");
  6.            s1.insert(6 , "Good ");
  7.            System.out.println(s1);
  8.         }
  9.    }

a) HelloGoodWorld
b) HellGoodoWorld
c) HellGood oWorld
d) Hello Good World

Answer: d
Clarification: The insert() method inserts one string into another. It is overloaded to accept values of all simple types, plus String and Objects. Sting is inserted into invoking object at specified position. “Good ” is inserted in “Hello World” T index 6 giving “Hello Good World”.
output:

$ javac output.java
$ java output 
Hello Good World

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.            StringBuffer s1 = new StringBuffer("Hello");
  6.            s1.insert(1,"Java");
  7.            System.out.println(s1);
  8.         }
  9.     }

a) hello
b) java
c) Hello Java
d) HJavaello

Answer: d
Clarification: Insert method will insert string at a specified position
Output:

$ javac output.java
$ java output
HJavaello

250+ TOP MCQs on Java.lang – Runtime & ClassLoader Classes and Answers

Java MCQs Runtime & ClassLoader classes of Java Programming Language.

1. Which of these classes encapsulate runtime environment?
a) Class
b) System
c) Runtime
d) ClassLoader

Answer: c
Clarification: None.

2. Which of the following exceptions is thrown by every method of Runtime class?
a) IOException
b) SystemException
c) SecurityException
d) RuntimeException

Answer: c
Clarification: Every method of Runtime class throws SecurityException.

3. Which of these methods returns the total number of bytes of memory available to the program?
a) getMemory()
b) TotalMemory()
c) SystemMemory()
d) getProcessMemory()

Answer: b
Clarification: TotalMemory() returns the total number of bytes available to the program.

4. Which of these Exceptions is thrown by loadClass() method of ClassLoader class?
a) IOException
b) SystemException
c) ClassFormatError
d) ClassNotFoundException

Answer: d
Clarification: None.

5. What will be the output of the following Java program?

  1.     class X 
  2.     {
  3.         int a;
  4.         double b;
  5.     }
  6.     class Y extends X 
  7.     {
  8. 	int c;
  9.     }
  10.     class Output 
  11.     {
  12.         public static void main(String args[]) 
  13.         {
  14.             X a = new X();
  15.             Y b = new Y();
  16.             Class obj;
  17.             obj = b.getClass();
  18.             System.out.print(obj.getSuperclass());
  19.         }
  20.     }

a) X
b) Y
c) class X
d) class Y

Answer: c
Clarification: getSuperClass() returns the super class of an object. b is an object of class Y which extends class X , Hence Super class of b is X. therefore class X is printed.
Output:

$ javac Output.java
$ java Output
class X

6. What will be the output of the following Java program?

  1.     class X 
  2.     {
  3.         int a;
  4.         double b;
  5.     }
  6.     class Y extends X 
  7.     {
  8. 	int c;
  9.     }
  10.     class Output 
  11.     {
  12.         public static void main(String args[]) 
  13.         {
  14.             X a = new X();
  15.             Y b = new Y();
  16.             Class obj;
  17.             obj = b.getClass();
  18.             System.out.print(b.equals(a));
  19.         }
  20.     }

a) 0
b) 1
c) true
d) false

Answer: d
Clarification: None.
Output:

$ javac Output.java
$ java Output
false

7. What will be the output of the following Java program?

  1.     class X 
  2.     {
  3.         int a;
  4.         double b;
  5.     }
  6.     class Y extends X 
  7.     {
  8. 	int c;
  9.     }
  10.     class Output 
  11.     {
  12.         public static void main(String args[]) 
  13.         {
  14.             X a = new X();
  15.             Y b = new Y();
  16.             Class obj;
  17.             obj = b.getClass();
  18.             System.out.print(obj.isInstance(a));
  19.         }
  20.     }

a) 0
b) 1
c) true
d) false

Answer: d
Clarification: Although class Y extends class X but still a is not considered related to Y. hence isInstance() returns false.
Output:

$ javac Output.java
$ java Output
false