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

250+ TOP MCQs on Java.util – Maps and Answers

Java MCQs on Maps of Java Programming Language.

1. Which of these object stores association between keys and values?
a) Hash table
b) Map
c) Array
d) String

Answer: b
Clarification: None.

2. Which of these classes provide implementation of map interface?
a) ArrayList
b) HashMap
c) LinkedList
d) DynamicList

Answer: b
Clarification: AbstractMap, WeakHashMap, HashMap and TreeMap provide implementation of map interface.

3. Which of these method is used to remove all keys/values pair from the invoking map?
a) delete()
b) remove()
c) clear()
d) removeAll()

Answer: b
Clarification: None.

4. Which of these method Map class is used to obtain an element in the map having specified key?
a) search()
b) get()
c) set()
d) look()

Answer: b
Clarification: None.

5. Which of these methods can be used to obtain set of all keys in a map?
a) getAll()
b) getKeys()
c) keyall()
d) keySet()

Answer: d
Clarification: keySet() methods is used to get a set containing all the keys used in a map. This method provides set view of the keys in the invoking map.

6. Which of these method is used add an element and corresponding key to a map?
a) put()
b) set()
c) redo()
d) add()

Answer: a
Clarification: Maps revolve around two basic operations – get() and put(). to put a value into a map, use put(), specifying the key and the value. To obtain a value, call get() , passing the key as an argument. The value is returned.

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

  1.     import java.util.*;
  2.     class Maps 
  3.     {
  4.         public static void main(String args[]) 
  5.         {
  6.             HashMap obj = new HashMap();
  7.             obj.put("A", new Integer(1));
  8.             obj.put("B", new Integer(2));
  9.             obj.put("C", new Integer(3));
  10.             System.out.println(obj);
  11.         }
  12.     }

a) {A 1, B 1, C 1}
b) {A, B, C}
c) {A-1, B-1, C-1}
d) {A=1, B=2, C=3}

Answer: d
Clarification: None.
Output:

$ javac Maps.java
$ java Maps 
{A=1, B=2, C=3}

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

  1.     import java.util.*;
  2.     class Maps 
  3.     {
  4.         public static void main(String args[]) 
  5.         {
  6.             HashMap obj = new HashMap();
  7.             obj.put("A", new Integer(1));
  8.             obj.put("B", new Integer(2));
  9.             obj.put("C", new Integer(3));
  10.             System.out.println(obj.keySet());
  11.         }
  12.     }

a) [A, B, C]
b) {A, B, C}
c) {1, 2, 3}
d) [1, 2, 3]

Answer: a
Clarification: keySet() method returns a set containing all the keys used in the invoking map. Here keys are characters A, B & C. 1, 2, 3 are the values given to these keys.
Output:

$ javac Maps.java
$ java Maps 
[A, B, C].

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

  1.     import java.util.*;
  2.     class Maps 
  3.     {
  4.         public static void main(String args[]) 
  5.         {
  6.             HashMap obj = new HashMap();
  7.             obj.put("A", new Integer(1));
  8.             obj.put("B", new Integer(2));
  9.             obj.put("C", new Integer(3));
  10.             System.out.println(obj.get("B"));
  11.         }
  12.     }

a) 1
b) 2
c) 3
d) null

Answer: b
Clarification: obj.get(“B”) method is used to obtain the value associated with key “B”, which is 2.
Output:

$ javac Maps.java
$ java Maps 
2

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

  1.     import java.util.*;
  2.     class Maps 
  3.     {
  4.         public static void main(String args[]) 
  5.         {
  6.             TreeMap obj = new TreeMap();
  7.             obj.put("A", new Integer(1));
  8.             obj.put("B", new Integer(2));
  9.             obj.put("C", new Integer(3));
  10.             System.out.println(obj.entrySet());
  11.         }
  12.     }

a) [A, B, C]
b) [1, 2, 3]
c) {A=1, B=2, C=3}
d) [A=1, B=2, C=3]

Answer: d
Clarification: obj.entrySet() method is used to obtain a set that contains the entries in the map. This method provides set view of the invoking map.
Output:

$ javac Maps.java
$ java Maps 
[A=1, B=2, C=3].

250+ TOP MCQs on isAlive(), Join() & Thread Synchronization and Answers

This set of Java Assessment Questions and Answers on “isAlive(), Join() & Thread Synchronization”.

1. Which of this method can be used to make the main thread to be executed last among all the threads?
a) stop()
b) sleep()
c) join()
d) call()

Answer: b
Clarification: By calling sleep() within main(), with long enough delay to ensure that all child threads terminate prior to the main thread.

2. Which of this method is used to find out that a thread is still running or not?
a) run()
b) Alive()
c) isAlive()
d) checkRun()

Answer: c
Clarification: The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise.

3. What is the default value of priority variable MIN_PRIORITY AND MAX_PRIORITY?
a) 0 & 256
b) 0 & 1
c) 1 & 10
d) 1 & 256

Answer: c
Clarification: None.

4. Which of these method waits for the thread to terminate?
a) sleep()
b) isAlive()
c) join()
d) stop()

Answer: c
Clarification: None.

5. Which of these method is used to explicitly set the priority of a thread?
a) set()
b) make()
c) setPriority()
d) makePriority()

Answer: c
Clarification: The default value of priority given to a thread is 5 but we can explicitly change that value between the permitted values 1 & 10, this is done by using the method setPriority().

6. What is synchronization in reference to a thread?
a) It’s a process of handling situations when two or more threads need access to a shared resource
b) It’s a process by which many thread are able to access same shared resource simultaneously
c) It’s a process by which a method is able to access many different threads simultaneously
d) It’s a method that allow too many threads to access any information require

Answer: a
Clarification: When two or more threads need to access the same shared resource, they need some way to ensure that the resource will be used by only one thread at a time, the process by which this is achieved is called synchronization

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

  1.     class newthread extends Thread 
  2.     {
  3. 	newthread()
  4.         {
  5. 	    super("My Thread");
  6. 	    start();
  7. 	}
  8. 	public void run()
  9.         {
  10. 	    System.out.println(this);
  11. 	}
  12.     }
  13.     class multithreaded_programing
  14.     {
  15.         public static void main(String args[])
  16.         {
  17.             new newthread();        
  18.         }
  19.     }

a) My Thread
b) Thread[My Thread,5,main]
c) Compilation Error
d) Runtime Error

Answer: b
Clarification: Although we have not created any object of thread class still we can make a thread pointing to main method, we can refer it by using this.
Output:

$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[My Thread,5,main].

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

  1.     class newthread extends Thread 
  2.     {
  3. 	Thread t;
  4. 	newthread()
  5.         {
  6. 	    t = new Thread(this,"My Thread");
  7. 	    t.start();
  8. 	}
  9. 	public void run()
  10.         {
  11.             try
  12.             {
  13.                 t.join()   
  14. 	        System.out.println(t.getName());
  15.             }
  16.             catch(Exception e)
  17.             {
  18.             System.out.print("Exception");
  19.             }
  20. 	}
  21.     }
  22.     class multithreaded_programing
  23.     {
  24.         public static void main(String args[])
  25.         {
  26.             new newthread();        
  27.         }
  28.     }

a) My Thread
b) Thread[My Thread,5,main]
c) Exception
d) Runtime Error

Answer: d
Clarification: join() method of Thread class waits for thread being called to finish or terminate, but here we have no condition which can terminate the thread, hence code ‘t.join()’ leads to runtime error and nothing will be printed on the screen.
Output:

$ javac multithreaded_programing.java
$ java multithreaded_programing

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

  1.     class newthread extends Thread
  2.     {
  3. 	Thread t;
  4. 	newthread()
  5.         {
  6. 	    t = new Thread(this,"New Thread");
  7. 	    t.start();
  8. 	}
  9. 	public void run()
  10.         {
  11. 	   System.out.println(t.isAlive());
  12. 	}
  13.     }
  14.     class multithreaded_programing
  15.     {
  16.         public static void main(String args[])
  17.         {
  18.             new newthread();        
  19.         }
  20.     }

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

Answer: c
Clarification: isAlive() method is used to check whether the thread being called is running or not, here thread is the main() method which is running till the program is terminated hence it returns true.
Output:

$ javac multithreaded_programing.java
$ java multithreaded_programing
true

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

  1.     class newthread extends Thread
  2.     {
  3. 	Thread t1,t2;
  4. 	newthread()
  5.         {
  6. 	    t1 = new Thread(this,"Thread_1");
  7. 	    t2 = new Thread(this,"Thread_2");
  8. 	    t1.start();
  9. 	    t2.start();
  10. 	}
  11. 	public void run()
  12.         {
  13. 	    t2.setPriority(Thread.MAX_PRIORITY);	
  14. 	    System.out.print(t1.equals(t2));
  15.         }    
  16.     }
  17.     class multithreaded_programing
  18.     {
  19.         public static void main(String args[])
  20.         {
  21.             new newthread();        
  22.         }
  23.     }

a) true
b) false
c) truetrue
d) falsefalse

Answer: d
Clarification: This program was previously done by using Runnable interface, here we have used Thread class. This shows both the method are equivalent, we can use any of them to create a thread.
Output:

$ javac multithreaded_programing.java
$ java multithreaded_programing
falsefalse