250+ TOP MCQs on Constructors & Garbage Collection and Answers

Java MCQs constructors and garbage collection of Java Programming Language.

1. What is the return type of Constructors?
a) int
b) float
c) void
d) none of the mentioned

Answer: d
Clarification: Constructors does not have any return type, not even void.

2. Which keyword is used by the method to refer to the object that invoked it?
a) import
b) catch
c) abstract
d) this

Answer: d
Clarification: this keyword can be used inside any method to refer to the current object. this is always a reference to the object on which the method was invoked.

3. Which of the following is a method having same name as that of its class?
a) finalize
b) delete
c) class
d) constructor

Answer: d
Clarification: A constructor is a method that initializes an object immediately upon creation. It has the same name as that of class in which it resides.

4. Which operator is used by Java run time implementations to free the memory of an object when it is no longer needed?
a) delete
b) free
c) new
d) none of the mentioned

Answer: d
Clarification: Java handles deallocation of memory automatically, we do not need to explicitly delete an element. Garbage collection only occurs during execution of the program. When no references to the object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.

5. Which function is used to perform some action when the object is to be destroyed?
a) finalize()
b) delete()
c) main()
d) none of the mentioned

Answer: a
Clarification: None.

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

  1.     class box 
  2.     {
  3.         int width;
  4.         int height;
  5.         int length;
  6.         int volume;
  7.         box() 
  8.         {
  9.             width = 5;
  10.             height = 5;
  11.             length = 6;
  12.         }
  13.         void volume() 
  14.         {
  15.              volume = width*height*length;
  16.         } 
  17.     }    
  18.     class constructor_output 
  19.     {
  20.         public static void main(String args[])
  21.         {
  22.             box obj = new box();
  23.             obj.volume();
  24.             System.out.println(obj.volume);
  25.         }
  26.    }

a) 100
b) 150
c) 200
d) 250

Answer: b
Clarification: None.
output:

$ constructor_output.java
$ constructor_output
150

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

  1. class San
  2. {
  3.      San()throws IOException
  4.      {
  5.  
  6.      } 
  7.  
  8. }
  9. class Foundry extends San
  10. {
  11.      Foundry()
  12.      {
  13.  
  14.      }
  15.      public static void main(String[]args)
  16.      {
  17.  
  18.      }
  19. }

a) compile time error
b) run time error
c) compile and runs fine
d) unreported exception java.io.IOException in default constructor

Answer: a
Clarification: If parent class constructor throws any checked exception, compulsory child class constructor should throw the same checked exception as its parent, otherwise code won’t compile.

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

  1.     class box 
  2.     {
  3.         int width;
  4.         int height;
  5.         int length;
  6.         int volume;
  7.         void finalize() 
  8.         {
  9.             volume = width*height*length;
  10.             System.out.println(volume);
  11.         }
  12.         protected void volume() 
  13.        {
  14.             volume = width*height*length;
  15.             System.out.println(volume);
  16.        } 
  17.     }    
  18.     class Output 
  19.     { 
  20.         public static void main(String args[])
  21.         {
  22.             box obj = new box();
  23.             obj.width=5;
  24.             obj.height=5;
  25.             obj.length=6;
  26.             obj.volume();
  27.         } 
  28.     }

a) 150
b) 200
c) Run time error
d) Compilation error

Answer: a
Clarification: None.
output:

$ javac Output.java
$ java Output
150

9. Which of the following statements are incorrect?
a) default constructor is called at the time of object declaration
b) constructor can be parameterized
c) finalize() method is called when a object goes out of scope and is no longer needed
d) finalize() method must be declared protected

Answer: c
Clarification: finalize() method is called just prior to garbage collection. it is not called when object goes out of scope.

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

  1.     class area 
  2.     {
  3.         int width;
  4.         int length;
  5.         int area;
  6.         void area(int width, int length) 
  7.         {
  8.             this.width = width;
  9.             this.length = length;
  10.         }
  11.  
  12.     }    
  13.     class Output 
  14.     {
  15.         public static void main(String args[])
  16.         {
  17.             area obj = new area();
  18.             obj.area(5 , 6);
  19.             System.out.println(obj.length + " " + obj.width);        
  20.         } 
  21.     }

a) 0 0
b) 5 6
c) 6 5
d) 5 5

Answer: c
Clarification: this keyword can be used inside any method to refer to the current object. this is always a reference to the object on which the method was invoked.
output:

$ javac Output.java
$ java Output
6 5

250+ TOP MCQs on Inheritance – 2 and Answers

This set of Java Interview Questions and Answers for freshers on “Inheritance – 2”.

1. What is not type of inheritance?
a) Single inheritance
b) Double inheritance
c) Hierarchical inheritance
d) Multiple inheritance

Answer: b
Clarification: Inheritance is way of acquiring attributes and methods of parent class. Java supports hierarchical inheritance directly.

2. Using which of the following, multiple inheritance in Java can be implemented?
a) Interfaces
b) Multithreading
c) Protected methods
d) Private methods

Answer: a
Clarification: Multiple inheritance in java is implemented using interfaces. Multiple interfaces can be implemented by a class.

3. All classes in Java are inherited from which class?
a) java.lang.class
b) java.class.inherited
c) java.class.object
d) java.lang.Object

Answer: d
Clarification: All classes in java are inherited from Object class. Interfaces are not inherited from Object Class.

4. In order to restrict a variable of a class from inheriting to subclass, how variable should be declared?
a) Protected
b) Private
c) Public
d) Static

Answer: b
Clarification: By declaring variable private, the variable will not be available in inherited to subclass.

5. If super class and subclass have same variable name, which keyword should be used to use super class?
a) super
b) this
c) upper
d) classname

Answer: a
Clarification: Super keyword is used to access hidden super class variable in subclass.

6. Static members are not inherited to subclass.
a) True
b) False

Answer: b
Clarification: Static members are also inherited to subclasses.

7. Which of the following is used for implementing inheritance through an interface?
a) inherited
b) using
c) extends
d) implements

Answer: d
Clarification: Interface is implemented using implements keyword. A concrete class must implement all the methods of an interface, else it must be declared abstract.

8. Which of the following is used for implementing inheritance through class?
a) inherited
b) using
c) extends
d) implements

Answer: c
Clarification: Class can be extended using extends keyword. One class can extend only one class. A final class cannot be extended.

9. What would be the result if a class extends two interfaces and both have a method with same name and signature? Lets assume that the class is not implementing that method.
a) Runtime error
b) Compile time error
c) Code runs successfully
d) First called method is executed successfully

Answer: b
Clarification: In case of such conflict, compiler will not be able to link a method call due to ambiguity. It will throw compile time error.

10. Does Java support multiple level inheritance?
a) True
b) False

Answer: a
Clarification: Java supports multiple level inheritance through implementing multiple interfaces.

Java for Interviews, here is complete set on Multiple Choice Questions and Answers on Java.

contest

250+ TOP MCQs on Java.lang – Rounding Functions and Answers

Java MCQs on rounding functions in Java Programming Language.

1. Which of these class provides various types of rounding functions?
a) Math
b) Process
c) System
d) Object

Answer: a
Clarification: None.

2. Which of these methods return a smallest whole number greater than or equal to variable X?
a) double ceil(double X)
b) double floor(double X)
c) double max(double X)
d) double min(double X)

Answer: a
Clarification: ceil(double X) returns the smallest whole number greater than or equal to variable X.

3. Which of these method returns a largest whole number less than or equal to variable X?
a) double ceil(double X)
b) double floor(double X)
c) double max(double X)
d) double min(double X)

Answer: b
Clarification: double floor(double X) returns a largest whole number less than or equal to variable X.

4. Which of function return absolute value of a variable?
a) abs()
b) absolute()
c) absolutevariable()
d) none of the mentioned

Answer: a
Clarification: abs() returns the absolute value of a variable.

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

  1.     class A 
  2.     {
  3.          int x;
  4.          int y;
  5.          void display() 
  6.          {
  7.               System.out.print(x + " " + y);
  8.          }
  9.     }
  10.     class Output 
  11.     {
  12.          public static void main(String args[]) 
  13.          {
  14.              A obj1 = new A();
  15.              A obj2 = new A();
  16.              obj1.x = 1;
  17.              obj1.y = 2;
  18.              obj2 = obj1.clone();
  19.              obj1.display();
  20.              obj2.display();
  21.          }
  22.     }

a) 1 2 0 0
b) 1 2 1 2
c) 0 0 0 0
d) System Dependent

Answer: b
Clarification: clone() method of object class is used to generate duplicate copy of the object on which it is called. Copy of obj1 is generated and stored in obj2.
Output:

$ javac Output.java
$ java Output
1 2 1 2

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

  1.     class Output 
  2.     {
  3.          public static void main(String args[]) 
  4.          {
  5.              double x = 3.14;  
  6.              int y = (int) Math.abs(x);
  7.              System.out.print(y);
  8.          }
  9.     }

a) 0
b) 3
c) 3.0
d) 3.1

Answer: b
Clarification: None.
Output:

$ javac Output.java
$ java Output
3

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

  1.     class Output 
  2.     {
  3.          public static void main(String args[]) 
  4.          {
  5.              double x = 3.14;  
  6.              int y = (int) Math.ceil(x);
  7.              System.out.print(y);
  8.          }
  9.     }

a) 0
b) 3
c) 3.0
d) 4

Answer: d
Clarification: ciel(double X) returns the smallest whole number greater than or equal to variable x.
Output:

$ javac Output.java
$ java Output
4

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

  1.     class Output 
  2.     {
  3.          public static void main(String args[]) 
  4.          {
  5.              double x = 3.14;  
  6.              int y = (int) Math.floor(x);
  7.              System.out.print(y);
  8.          }
  9.     }

a) 0
b) 3
c) 3.0
d) 4

Answer: b
Clarification: double floor(double X) returns a largest whole number less than or equal to variable X. Here the smallest whole number less than 3.14 is 3.
Output:

$ javac Output.java
$ java Output
3

250+ TOP MCQs on Java.util – ArrayList Class and Answers

Java MCQs on ArrayList class of Java Programming Language.

1. Which of these standard collection classes implements a dynamic array?
a) AbstractList
b) LinkedList
c) ArrayList
d) AbstractSet

Answer: c
Clarification: ArrayList class implements a dynamic array by extending AbstractList class.

2. Which of these class can generate an array which can increase and decrease in size automatically?
a) ArrayList()
b) DynamicList()
c) LinkedList()
d) MallocList()

Answer: a
Clarification: None.

3. Which of these method can be used to increase the capacity of ArrayList object manually?
a) Capacity()
b) increaseCapacity()
c) increasecapacity()
d) ensureCapacity()

Answer: d
Clarification: When we add an element, the capacity of ArrayList object increases automatically, but we can increase it manually to specified length x by using function ensureCapacity(x);

4. Which of these method of ArrayList class is used to obtain present size of an object?
a) size()
b) length()
c) index()
d) capacity()

Answer: a
Clarification: None.

5. Which of these methods can be used to obtain a static array from an ArrayList object?
a) Array()
b) covertArray()
c) toArray()
d) covertoArray()

Answer: c
Clarification: None.

6. Which of these method is used to reduce the capacity of an ArrayList object?
a) trim()
b) trimSize()
c) trimTosize()
d) trimToSize()

Answer: d
Clarification: trimTosize() is used to reduce the size of the array that underlines an ArrayList object.

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

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

a) [A, B, C, D]
b) [A, D, B, C]
c) [A, D, C]
d) [A, B, C]

Answer: b
Clarification: obj is an object of class ArrayList hence it is an dynamic array which can increase and decrease its size. obj.add(“X”) adds to the array element X and obj.add(1,”X”) adds element x at index position 1 in the list, Hence obj.add(1,”D”) stores D at index position 1 of obj and shifts the previous value stored at that position by 1.
Output:

$ javac Arraylist.java
$ java Arraylist
[A, D, B, C].

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

  1.     import java.util.*;
  2.     class Output 
  3.     {
  4.         public static void main(String args[]) 
  5.         {
  6.             ArrayList obj = new ArrayList();
  7.             obj.add("A");
  8.             obj.add(0, "B");
  9.             System.out.println(obj.size());
  10.         }
  11.     }

a) 0
b) 1
c) 2
d) Any Garbage Value

Answer: c
Clarification: None.
Output:

$ javac Output.java
$ java Output
2

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

  1.     import java.util.*;
  2.     class Output 
  3.     {
  4.         public static void main(String args[]) 
  5.         {
  6.             ArrayList obj = new ArrayList();
  7.             obj.add("A");
  8.             obj.ensureCapacity(3);
  9.             System.out.println(obj.size());
  10.         }
  11.     }

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

Answer: a
Clarification: Although obj.ensureCapacity(3); has manually increased the capacity of obj to 3 but the value is stored only at index 0, therefore obj.size() returns the total number of elements stored in the obj i:e 1, it has nothing to do with ensureCapacity().
Output:

$ javac Output.java
$ java Output
1

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

  1.     class Output 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             ArrayList obj = new ArrayList();
  6.             obj.add("A");
  7.             obj.add("D");
  8.             obj.ensureCapacity(3);
  9.             obj.trimToSize();
  10.             System.out.println(obj.size());
  11.          }      
  12.     }

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

Answer: b
Clarification: trimTosize() is used to reduce the size of the array that underlines an ArrayList object.
Output:

$ javac Output.java
$ java Output
2

250+ TOP MCQs on Exceptions Types and Answers

Java MCQs on Exceptions types in Java Programming Language.

1. Which of these is a super class of all exceptional type classes?
a) String
b) RuntimeExceptions
c) Throwable
d) Cacheable

Answer: c
Clarification: All the exception types are subclasses of the built in class Throwable.

2. Which of these class is related to all the exceptions that can be caught by using catch?
a) Error
b) Exception
c) RuntimeExecption
d) All of the mentioned

Answer: b
Clarification: Error class is related to java run time error that can’t be caught usually, RuntimeExecption is subclass of Exception class which contains all the exceptions that can be caught.

3. Which of these class is related to all the exceptions that cannot be caught?
a) Error
b) Exception
c) RuntimeExecption
d) All of the mentioned

Answer: a
Clarification: Error class is related to java run time error that can’t be caught usually, RuntimeExecption is subclass of Exception class which contains all the exceptions that can be caught.

4. Which of these handles the exception when no catch is used?
a) Default handler
b) finally
c) throw handler
d) Java run time system

Answer: a
Clarification: None.

5. What exception thrown by parseInt() method?
a) ArithmeticException
b) ClassNotFoundException
c) NullPointerException
d) NumberFormatException

Answer: d
Clarification: parseInt() method parses input into integer. The exception thrown by this method is NumberFormatException.

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

  1.     class exception_handling 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             try 
  6.             {
  7.                 System.out.print("Hello" + " " + 1 / 0);
  8.             }
  9.             finally 
  10.             {
  11.         	System.out.print("World");        	
  12.             }
  13.         }
  14.     }

a) Hello
b) World
c) Compilation Error
d) First Exception then World

Answer: d
Clarification: None.
Output:

$ javac exception_handling.java
$ java exception_handling
Exception in thread "main" java.lang.ArithmeticException: / by zero
World

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

  1.     class exception_handling 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             try 
  6.             {
  7.                 int i, sum;
  8.                 sum = 10;
  9.                 for (i = -1; i < 3 ;++i) 
  10.                 {
  11.                     sum = (sum / i);
  12.                 System.out.print(i);
  13.                 }
  14.             }
  15.             catch(ArithmeticException e) 
  16.             {     	
  17.                 System.out.print("0");
  18.             }
  19.         }
  20.     }

a) -1
b) 0
c) -10
d) -101

Answer: c
Clarification: For the 1st iteration -1 is displayed. The 2nd exception is caught in catch block and 0 is displayed.
Output:

$ javac exception_handling.java
$ java exception_handling
-10

contest

250+ TOP MCQs on Regular Expression and Answers

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

1. Which of the following is not a class of java.util.regex?
a) Pattern class
b) matcher class
c) PatternSyntaxException
d) Regex class

Answer: d
Clarification: java.util.regex consists 3 classes. PatternSyntaxException indicates syntax error in regex.

2. What is the significance of Matcher class for regular expression in java?
a) interpretes pattern in the string
b) Performs match in the string
c) interpreted both pattern and performs match operations in the string
d) None of the mentioned.

Answer: c
Clarification: macther() method is invoked using matcher object which interpretes pattern and performs match operations in the input string.

3. Object of which class is used to compile regular expression?
a) Pattern class
b) Matcher class
c) PatternSyntaxException
d) None of the mentioned

Answer: a
Clarification: object of Pattern class can represent compiled regular expression.

4. Which capturing group can represent the entire expression?
a) group *
b) group 0
c) group * or group 0
d) None of the mentioned

Answer: b
Clarification: Group 0 is a special group which represents the entire expression.

5. groupCount reports a total number of Capturing groups.
a) True
b) False

Answer: a
Clarification: groupCount reports total number of Capturing groups. this does not include special group, group 0.

6. Which of the following matches nonword character using regular expression in java?
a) w
b) W
c) s
d) S

Answer: b
Clarification: W matches nonword characters. [0-9], [A-Z] and _ (underscore) are word characters. All other than these characters are nonword characters.

7. Which of the following matches end of the string using regular expression in java?
a) z
b) \
c) *
d) Z

Answer: a
Clarification: z is used to match end of the entire string in regular expression in java.

8. What does public int end(int group) return?
a) offset from last character of the subsequent group
b) offset from first character of the subsequent group
c) offset from last character matched
d) offset from first character matched

Answer: a
Clarification: public int end(int group) returns offset from the last character of the subsequent group.

9. what does public String replaceAll(string replace) do?
a) Replace all characters that matches pattern with a replacement string
b) Replace first subsequence that matches pattern with a replacement string
c) Replace all other than first subsequence of that matches pattern with a replacement string
d) Replace every subsequence of the input sequence that matches pattern with a replacement string

Answer: d
Clarification: replaceAll method replaces every subsequence of the sequence that matches pattern with a replacement string.

10. What does public int start() return?
a) returns start index of the input string
b) returns start index of the current match
c) returns start index of the previous match
d) none of the mentioned

Answer: c
Clarification: public int start() returns index of the previous match in the input string.