Advanced 250+ TOP MCQs on Reflection API and Answers

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

1. What are the components of a marker interface?
a) Fields and methods
b) No fields, only methods
c) Fields, no methods
d) No fields, No methods

Answer: d
Clarification: Marker interface in Java is an empty interface in Java.

2. Which of the following is not a marker interface?
a) Serializable
b) Cloneable
c) Remote
d) Reader

Answer: d
Clarification: Reader is not a marker interface. Serializable, Cloneable and Remote interfaces are marker interface.

3. What is not the advantage of Reflection?
a) Examine a class’s field and method at runtime
b) Construct an object for a class at runtime
c) Examine a class’s field at compile time
d) Examine an object’s class at runtime

Answer: c
Clarification: Reflection inspects classes, interfaces, fields and methods at a runtime.

4. How private method can be called using reflection?
a) getDeclaredFields
b) getDeclaredMethods
c) getMethods
d) getFields

Answer: b
Clarification: getDeclaredMethods gives instance of java.lang.reflect.Method.

5. How private field can be called using reflection?
a) getDeclaredFields
b) getDeclaredMethods
c) getMethods
d) getFields

Answer: a
Clarification: getDeclaredFields gives instance of java.lang.reflect.Fields.

6. What is used to get class name in reflection?
a) getClass().getName()
b) getClass().getFields()
c) getClass().getDeclaredFields()
d) new getClass()

Answer: a
Clarification: getClass().getName() is used to get a class name from object in reflection.

7. How method can be invoked on unknown object?
a) obj.getClass().getDeclaredMethod()
b) obj.getClass().getDeclaredField()
c) obj.getClass().getMethod()
d) obj.getClass().getObject()

Answer: c
Clarification: obj.getClass().getMethod is used to invoke a method on unknown object obj.

8. How to get the class object of associated class using Reflection?
a) Class.forName(“className”)
b) Class.name(“className”)
c) className.getClass()
d) className.getClassName()

Answer: a
Clarification: forName(String className) returns the Class object associated with the class or interface with the given string name.

9. What does Class.forName(“myreflection.Foo”).getInstance() return?
a) An array of Foo objects
b) class object of Foo
c) Calls the getInstance() method of Foo class
d) Foo object

Answer: d
Clarification: Class.forName(“myreflection.Foo”) returns the class object of Foo and getInstance() would return a new object.

10. What does foo.getClass().getMethod(“doSomething”, null) return?
a) doSomething method instance
b) Method is returned and we can call the method as method.invoke(foo,null);
c) Class object
d) Exception is thrown

Answer: b
Clarification: foo.getClass().getMethod() returns a method and we can call the method using method.invoke();

250+ TOP MCQs on Data Type-BigDecimal and Answers

This set of Tough Java Questions and Answers on “Data Type-BigDecimal”.

1. Which of the following is the advantage of BigDecimal over double?
a) Syntax
b) Memory usage
c) Garbage creation
d) Precision

Answer: d
Clarification: BigDecimal has unnatural syntax, needs more memory and creates a great amount of garbage. But it has a high precision which is useful for some calculations like money.

2. Which of the below data type doesn’t support overloaded methods for +,-,* and /?
a) int
b) float
c) double
d) BigDecimal

Answer: d
Clarification: int, float, double provide overloaded methods for +,-,* and /. BigDecimal does not provide these overloaded methods.

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

  1.    double a = 0.02;
  2.    double b = 0.03;
  3.    double c = b - a;
  4.    System.out.println(c);
  5.  
  6.    BigDecimal _a = new BigDecimal("0.02");
  7.    BigDecimal _b = new BigDecimal("0.03");
  8.    BigDecimal _c = b.subtract(_a);
  9.    System.out.println(_c);

a)

   0.009999999999999998
   0.01

b)

   0.01
   0.009999999999999998

c)

   0.01
   0.01

d)

   0.009999999999999998
   0.009999999999999998

Answer: a
Clarification: BigDecimal provides more precision as compared to double. Double is faster in terms of performance as compared to BigDecimal.

 
 

4. What is the base of BigDecimal data type?
a) Base 2
b) Base 8
c) Base 10
d) Base e

Answer: c
Clarification: A BigDecimal is n*10^scale where n is an arbitrary large signed integer. Scale can be thought of as the number of digits to move the decimal point to left or right.

5. What is the limitation of toString() method of BigDecimal?
a) There is no limitation
b) toString returns null
c) toString returns the number in expanded form
d) toString uses scientific notation

Answer: d
Clarification: toString() of BigDecimal uses scientific notation to represent numbers known as canonical representation. We must use toPlainString() to avoid scientific notation.

6. Which of the following is not provided by BigDecimal?
a) scale manipulation
b) + operator
c) rounding
d) hashing

Answer: b
Clarification: toBigInteger() converts BigDecimal to a BigInteger.toBigIntegerExact() converts this BigDecimal to a BigInteger by checking for lost information.

7. BigDecimal is a part of which package?
a) java.lang
b) java.math
c) java.util
d) java.io

Answer: b
Clarification: BigDecimal is a part of java.math. This package provides various classes for storing numbers and mathematical operations.

8. What is BigDecimal.ONE?
a) wrong statement
b) custom defined statement
c) static variable with value 1 on scale 10
d) static variable with value 1 on scale 0

Answer: d
Clarification: BigDecimal.ONE is a static variable of BigDecimal class with value 1 on scale 0.

9. Which class is a library of functions to perform arithmetic operations of BigInteger and BigDecimal?
a) MathContext
b) MathLib
c) BigLib
d) BigContext

Answer: a
Clarification: MathContext class is a library of functions to perform arithmetic operations of BigInteger and BigDecimal.

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

  1. public class AddDemo 
  2. {
  3. 	public static void main(String args[]) 
  4.         {
  5. 		BigDecimal b = new BigDecimal("23.43");
  6. 		BigDecimal br = new BigDecimal("24");
  7. 		BigDecimal bres = b.add(new BigDecimal("450.23"));
  8. 		System.out.println("Add: "+bres);
  9.  
  10. 		MathContext mc = new MathContext(2, RoundingMode.DOWN);
  11. 		BigDecimal bdecMath = b.add(new BigDecimal("450.23"), mc);
  12. 		System.out.println("Add using MathContext: "+bdecMath);
  13. 	}
  14. }

a) Compilation failure
b)

Add: 473.66
Add using MathContext: 4.7E+2

c)

Add 4.7E+2
Add using MathContext: 473.66

d) Runtime exception

Answer: b
Clarification: add() adds the two numbers, MathContext provides library for carrying out various arithmetic operations.

To practice tough questions and answers on all areas of Java, here is complete set on Multiple Choice Questions and Answers on Java.

contest

250+ TOP MCQs on Heap and Garbage Collection and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) on “Heap and Garbage Collection”.

1. Which of the following has the highest memory requirement?
a) Heap
b) Stack
c) JVM
d) Class

Answer: c
Clarification: JVM is the super set which contains heap, stack, objects, pointers, etc.

2. Where is a new object allocated memory?
a) Young space
b) Old space
c) Young or Old space depending on space availability
d) JVM

Answer: a
Clarification: A new object is always created in young space. Once young space is full, a special young collection is run where objects which have lived long enough are moved to old space and memory is freed up in young space for new objects.

3. Which of the following is a garbage collection technique?
a) Cleanup model
b) Mark and sweep model
c) Space management model
d) Sweep model

Answer: b
Clarification: A mark and sweep garbage collection consists of two phases, the mark phase and the sweep phase. I mark phase all the objects reachable by java threads, native handles and other root sources are marked alive and others are garbage. In sweep phase, the heap is traversed to find gaps between live objects and the gaps are marked free list used for allocating memory to new objects.

4. What is -Xms and -Xmx while starting jvm?
a) Initial; Maximum memory
b) Maximum; Initial memory
c) Maximum memory
d) Initial memory

Answer: a
Clarification: JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory. java -Xmx2048m -Xms256m.

5. Which exception is thrown when java is out of memory?
a) MemoryFullException
b) MemoryOutOfBoundsException
c) OutOfMemoryError
d) MemoryError

Answer: c
Clarification: The Xms flag has no default value, and Xmx typically has a default value of 256MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.

6. How to get prints of shared object memory maps or heap memory maps for a given process?
a) jmap
b) memorymap
c) memorypath
d) jvmmap

Answer: a
Clarification: We can use jmap as jmap -J-d64 -heap pid.

7. What happens to the thread when garbage collection kicks off?
a) The thread continues its operation
b) Garbage collection cannot happen until the thread is running
c) The thread is paused while garbage collection runs
d) The thread and garbage collection do not interfere with each other

Answer: c
Clarification: The thread is paused when garbage collection runs which slows the application performance.

8. Which of the below is not a Java Profiler?
a) JVM
b) JConsole
c) JProfiler
d) Eclipse Profiler

Answer: a
Clarification: Memory leak is like holding a strong reference to an object although it would never be needed anymore. Objects that are reachable but not live are considered memory leaks. Various tools help us to identify memory leaks.

9. Which of the below is not a memory leak solution?
a) Code changes
b) JVM parameter tuning
c) Process restart
d) GC parameter tuning

Answer: c
Clarification: Process restart is not a permanent fix to memory leak problem. The problem will resurge again.

10. Garbage Collection can be controlled by a program?
a) True
b) False

Answer: b
Clarification: Garbage Collection cannot be controlled by a program.

250+ TOP MCQs on String Comparison and Answers

Java MCQs on String comparision in Java Programming Language.

1. Which of these method of class String is used to compare two String objects for their equality?
a) equals()
b) Equals()
c) isequal()
d) Isequal()

Answer: a
Clarification: None.

2. Which of these methods is used to compare a specific region inside a string with another specific region in another string?
a) regionMatch()
b) match()
c) RegionMatches()
d) regionMatches()

Answer: d
Clarification: None.

3. Which of these methods of class String is used to check whether a given object starts with a particular string literal?
a) startsWith()
b) endsWith()
c) Starts()
d) ends()

Answer: a
Clarification: Method startsWith() of string class is used to check whether the String in question starts with a specified string. It is a specialized form of method regionMatches().

4. What is the value returned by function compareTo() if the invoking string is less than the string compared?
a) zero
b) value less than zero
c) value greater than zero
d) none of the mentioned

Answer: b
Clarification: compareTo() function returns zero when both the strings are equal, it returns a value less than zero if the invoking string is less than the other string being compared and value greater than zero when invoking string is greater than the string compared to.

5. Which of these data type value is returned by equals() method of String class?
a) char
b) int
c) boolean
d) all of the mentioned

Answer: c
Clarification: equals() method of string class returns boolean value true if both the string are equal and false if they are unequal.

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.            String c = "Hello i love java";
  6.            boolean var;
  7.            var = c.startsWith("hello");
  8.            System.out.println(var);
  9.         }
  10.     }

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

Answer: b
Clarification: startsWith() method is case sensitive “hello” and “Hello” are treated differently, hence false is stored in var.
Output:

$ javac output.java
$ java output
false

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.            String s1 = "Hello i love java";
  6.            String s2 = new String(s1);
  7.            System.out.println((s1 == s2) + " " + s1.equals(s2));
  8.         }
  9.     }

a) true true
b) false false
c) true false
d) false true

Answer: d
Clarification: The == operator compares two object references to see whether they refer to the same instance, where as equals() compares the content of the two objects.
Output:

$ javac output.java
$ java output
false true

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.            String s1 = "Hello";
  6.            String s2 = new String(s1);
  7.            String s3 = "HELLO";
  8.            System.out.println(s1.equals(s2) + " " + s2.equals(s3));
  9.         }
  10.     }

a) true true
b) false false
c) true false
d) false true

Answer: c
Clarification: None.
Output:

$ javac output.java
$ java output
true false

9. In the following Java code, which code fragment should be inserted at line 3 so that the output will be: “123abc 123abc”?

 1. StringBuilder sb1 = new StringBuilder("123");
 2. String s1 = "123";
 3.  // insert code here
 4. System.out.println(sb1 + " " + s1);

a) sb1.append(“abc”); s1.append(“abc”);
b) sb1.append(“abc”); s1.concat(“abc”);
c) sb1.concat(“abc”); s1.append(“abc”);
d) sb1.append(“abc”); s1 = s1.concat(“abc”);

Answer: d
Clarification: append() is stringbuffer method and concat is String class method.
append() is stringbuffer method and concat is String class method.

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.              String chars[] = {"a", "b", "c", "a", "c"};
  6.              for (int i = 0; i < chars.length; ++i)
  7.                  for (int j = i + 1; j < chars.length; ++j)
  8.                      if(chars[i].compareTo(chars[j]) == 0)
  9.                          System.out.print(chars[j]); 
  10.         }
  11.    }

a) ab
b) bc
c) ca
d) ac

Answer: d
Clarification: compareTo() function returns zero when both the strings are equal, it returns a value less than zero if the invoking string is less than the other string being compared and value greater than zero when invoking string is greater than the string compared to.
output:

$ javac output.java
$ java output  
ac

250+ TOP MCQs on Java.lang – Character Wrapper Advance and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) on “Character Wrapper Advance”.

1. Which of these methods of Character wrapper can be used to obtain the char value contained in Character object.
a) get()
b) getVhar()
c) charValue()
d) getCharacter()

Answer: c
Clarification: To obtain the char value contained in a Character object, we use charValue() method.

2. Which of the following constant are defined in Character wrapper?
a) MAX_RADIX
b) MAX_VALUE
c) TYPE
d) All of the mentioned

Answer: d
Clarification: Character wrapper defines 5 constants – MAX_RADIX, MIN_RADIX, MAX_VALUE, MIN_VALUE & TYPE.

3. Which of these is a super class of Character wrapper?
a) Long
b) Digits
c) Float
d) Number

Answer: d
Clarification: Number is an abstract class containing subclasses Double, Float, Byte, Short, Character, Integer and Long.

4. Which of these methods is used to know whether a given Character object is part of Java’s Identifiers?
a) isIdentifier()
b) isJavaIdentifier()
c) isJavaIdentifierPart()
d) none of the mentioned

Answer: c
Clarification: None.

5. Which of these coding techniques is used by method isDefined()?
a) Latin
b) ASCII
c) ANSI
d) UNICODE

Answer: d
Clarification: isDefined() returns true if ch is defined by Unicode. Otherwise, it returns false.

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

  1.     class Output 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             int a = Character.MAX_VALUE;
  6.             System.out.print((char)a);
  7.         }
  8.     }

a) <
b) >
c) ?
d) $

Answer: c
Clarification: Character.MAX_VALUE returns the largest character value, which is of character ‘?’.
Output:

$ javac Output.java
$ java Output
?

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

  1.     class Output
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.             int a = Character.MIN_VALUE;
  6.             System.out.print((char)a);
  7.         }
  8.     }

a) <
b) !
c) @
d) Space

Answer: d
Clarification: Character.MIN_VALUE returns the smallest character value, which is of space character ‘ ‘.
Output:

$ javac Output.java
$ java Output

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

  1.     class Output 
  2.     {
  3.          public static void main(String args[])
  4.          {
  5.              char a[] = {'a', '5', 'A', ' '};   
  6.              System.out.print(Character.isDigit(a[0])+ " ");
  7.              System.out.print(Character.isWhitespace(a[3])+ " ");
  8.              System.out.print(Character.isUpperCase(a[2]));
  9.         }
  10.     }

a) true false true
b) false true true
c) true true false
d) false false false

Answer: b
Clarification: Character.isDigit(a[0]) checks for a[0], whether it is a digit or not, since a[0] i:e ‘a’ is a character false is returned. a[3] is a whitespace hence Character.isWhitespace(a[3]) returns a true. a[2] is an uppercase letter i:e ‘A’ hence Character.isUpperCase(a[2]) returns true.
Output:

$ javac Output.java
$ java Output
false true true

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

  1.     class Output
  2.     {
  3.         public static void main(String args[])
  4.         {
  5. 	    char a = (char) 98;
  6.             a = Character.toUpperCase(a);
  7.             System.out.print(a);
  8.         }
  9.     }

a) b
b) c
c) B
d) C

Answer: c
Clarification: None.
Output:

$ javac Output.java
$ java Output
B

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

  1.     class Output
  2.     {
  3.         public static void main(String args[])
  4.         {
  5. 	    char a = '@';
  6.             boolean x = Character.isLetter(a);
  7.             System.out.print(x);
  8.         }
  9.     }

a) true
b) false
c) @
d) B

Answer: b
Clarification: None.
Output:

$ javac Output.java
$ java Output
false

250+ TOP MCQs on Data Structures-List and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) on “Data Structures-List”.

1. How can we remove an object from ArrayList?
a) remove() method
b) using Iterator
c) remove() method and using Iterator
d) delete() method

Answer: c
Clarification: There are 2 ways to remove an object from ArrayList. We can use overloaded method remove(int index) or remove(Object obj). We can also use an Iterator to remove the object.

2. How to remove duplicates from List?
a) HashSet listToSet = new HashSet(duplicateList);
b) HashSet listToSet = duplicateList.toSet();
c) HashSet listToSet = Collections.convertToSet(duplicateList);
d) HashSet listToSet = duplicateList.getSet();

Answer: a
Clarification: Duplicate elements are allowed in List. Set contains unique objects.

3. How to sort elements of ArrayList?
a) Collection.sort(listObj);
b) Collections.sort(listObj);
c) listObj.sort();
d) Sorter.sortAsc(listObj);

Answer: b
Clarification: Collections provides a method to sort the list. The order of sorting can be defined using Comparator.

4. When two threads access the same ArrayList object what is the outcome of the program?
a) Both are able to access the object
b) ConcurrentModificationException is thrown
c) One thread is able to access the object and second thread gets Null Pointer exception
d) One thread is able to access the object and second thread will wait till control is passed to the second one

Answer: b
Clarification: ArrayList is not synchronized. Vector is the synchronized data structure.

5. How is Arrays.asList() different than the standard way of initialising List?
a) Both are same
b) Arrays.asList() throws compilation error
c) Arrays.asList() returns a fixed length list and doesn’t allow to add or remove elements
d) We cannot access the list returned using Arrays.asList()

Answer: c
Clarification: List returned by Arrays.asList() is a fixed length list which doesn’t allow us to add or remove element from it.add() and remove() method will throw UnSupportedOperationException if used.

6. What is the difference between length() and size() of ArrayList?
a) length() and size() return the same value
b) length() is not defined in ArrayList
c) size() is not defined in ArrayList
d) length() returns the capacity of ArrayList and size() returns the actual number of elements stored in the list

Answer: d
Clarification: length() returns the capacity of ArrayList and size() returns the actual number of elements stored in the list which is always less than or equal to capacity.

7. Which class provides thread safe implementation of List?
a) ArrayList
b) CopyOnWriteArrayList
c) HashList
d) List

Answer: b
Clarification: CopyOnWriteArrayList is a concurrent collection class. Its very efficient if ArrayList is mostly used for reading purpose because it allows multiple threads to read data without locking, which was not possible with synchronized ArrayList.

8. Which of the below is not an implementation of List interface?
a) RoleUnresolvedList
b) Stack
c) AttibuteList
d) SessionList

Answer: d
Clarification: SessionList is not an implementation of List interface. The others are concrete classes of List.

9. What is the worst case complexity of accessing an element in ArrayList?
a) O(n)
b) O(1)
c) O(nlogn)
d) O(2)

Answer: b
Clarification: ArrayList has O(1) complexity for accessing an element in ArrayList. O(n) is the complexity for accessing an element from LinkedList.

10. When an array is passed to a method, will the content of the array undergo changes with the actions carried within the function?
a) True
b) False

Answer: a
Clarification: If we make a copy of array before any changes to the array the content will not change. Else the content of the array will undergo changes.

  1. public void setMyArray(String[] myArray)
  2. {
  3. 	if(myArray == null)
  4.         {
  5. 		this.myArray = new String[0];	
  6. 	} 
  7.         else 
  8.         {
  9. 		this.myArray = Arrays.copyOf(newArray, newArray.length);
  10. 	} 
  11. }