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

250+ TOP MCQs on Finally & Built in Exceptions and Answers

Java MCQs on keyword finally and built in exceptions of Java Programming Language.

1. Which of these clause will be executed even if no exceptions are found?
a) throws
b) finally
c) throw
d) catch

Answer: b
Clarification: finally keyword is used to define a set of instructions that will be executed irrespective of the exception found or not.

2. A single try block must be followed by which of these?
a) finally
b) catch
c) finally & catch
d) none of the mentioned

Answer: c
Clarification: try block can be followed by any of finally or catch block, try block checks for exceptions and work is performed by finally and catch block as per the exception.

3. Which of these exceptions handles the divide by zero error?
a) ArithmeticException
b) MathException
c) IllegalAccessException
d) IllegarException

Answer: a
Clarification: None.

4. Which of these exceptions will occur if we try to access the index of an array beyond its length?
a) ArithmeticException
b) ArrayException
c) ArrayIndexException
d) ArrayIndexOutOfBoundsException

Answer: d
Clarification: ArrayIndexOutOfBoundsException is a built in exception that is caused when we try to access an index location which is beyond the length of an array.

5. 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 a = args.length;
  8.                 int b = 10 / a;
  9.                 System.out.print(a);
  10.             }
  11.             catch (ArithmeticException e) 
  12.             {
  13.                     System.out.println("1");
  14.             }
  15.         }
  16.     }

Note : Execution command line : $ java exception_handling
a) 0
b) 1
c) Compilation Error
d) Runtime Error

Answer: b
Clarification: None.
Output:

$ javac exception_handling.java
$ java exception_handling
1

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.                 throw new NullPointerException ("Hello");
  8.             }
  9.             catch(ArithmeticException e)
  10.             {
  11.         	System.out.print("B");        	
  12.             }
  13.         }
  14.     }

a) A
b) B
c) Compilation Error
d) Runtime Error

Answer: d
Clarification: Try block is throwing NullPointerException but the catch block is used to counter Arithmetic Exception. Hence NullPointerException occurs since no catch is there which can handle it, runtime error occurs.
Output:

$ javac exception_handling.java
$ java exception_handling
Exception in thread "main" java.lang.NullPointerException: Hello

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 a = 1;
  8.                     int b = 10 / a;
  9.                     try 
  10.                     {
  11.                          if (a == 1)
  12.                              a = a / a - a;
  13.                          if (a == 2) 
  14.                          {
  15.                              int c[] = {1};
  16.                              c[8] = 9;
  17.                          }
  18.                     }
  19.                     finally 
  20.                     {
  21.                         System.out.print("A");
  22.                     }
  23.                 }
  24.                 catch (Exception e) 
  25.                 {
  26.                         System.out.println("B");
  27.                 }
  28.             }
  29.         }

a) A
b) B
c) AB
d) BA

Answer: a
Clarification: The inner try block does not have a catch which can tackle ArrayIndexOutOfBoundException hence finally is executed which prints ‘A’ the outer try block does have catch for ArrayIndexOutOfBoundException exception but no such exception occurs in it hence its catch is never executed and only ‘A’ is printed.
Output:

$ javac exception_handling.java
$ java exception_handling
A

8. 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 a = args.length;
  8.                 int b = 10 / a;
  9.                 System.out.print(a);
  10.                 try 
  11.                 {
  12.                      if (a == 1)
  13.                          a = a / a - a;
  14.                      if (a == 2) 
  15.                      {
  16.                          int []c = {1};
  17.                          c[8] = 9;
  18.                      }
  19.                 }
  20.                 catch (ArrayIndexOutOfBoundException e) 
  21.                 {
  22.                     System.out.println("TypeA");
  23.                 }
  24.             catch (ArithmeticException e) 
  25.             {
  26.                     System.out.println("TypeB");
  27.             }
  28.         }
  29.     }

Note: Execution command line: $ java exception_handling one two
a) TypeA
b) TypeB
c) Compilation Error
d) Runtime Error

Answer: c
Clarification: try without catch or finally
Output:

$ javac exception_handling.java
$ java exception_handling
Main.java:9: error: 'try' without 'catch', 'finally' or resource declarations

250+ TOP MCQs on ActionEvent & AdjustmentEvent Class and Answers

Java MCQs on ActionEvent & AdjustmentEvent class in Java Programming Language.

1. Which of these events is generated when a button is pressed?
a) ActionEvent
b) KeyEvent
c) WindowEvent
d) AdjustmentEvent

Answer: a
Clarification: Action event is generated when a button is pressed, a list item is double-clicked or a menu item is selected.

2. Which of these methods can be used to obtain the command name for invoking ActionEvent object?
a) getCommand()
b) getActionCommand()
c) getActionEvent()
d) getActionEventCommand()

Answer: b
Clarification: None.

3. Which of these are integer constants defined in ActionEvent class?
a) ALT_MASK
b) CTRL_MASK
c) SHIFT_MASK
d) All of the mentioned

Answer: d
Clarification: Action event defines 4 integer constants ALT_MASK, CTRL_MASK, SHIFT_MASK and ACTION_PERFORMED

4. Which of these methods can be used to know which key is pressed?
a) getKey()
b) getModifier()
c) getActionKey()
d) getActionEvent()

Answer: b
Clarification: The getModifiers() methods returns a value that indicates which modifiers keys (ALT, CTRL, META, SHIFT) were pressed when the event was generated.

5. Which of these events is generated by scroll bar?
a) ActionEvent
b) KeyEvent
c) WindowEvent
d) AdjustmentEvent

Answer: d
Clarification: None.

6. Which of these methods can be used to determine the type of adjustment event?
a) getType()
b) getEventType()
c) getAdjustmentType()
d) getEventObjectType()

Answer: c
Clarification: None.

7. Which of these methods can be used to know the degree of adjustment made by the user?
a) getValue()
b) getAdjustmentType()
c) getAdjustmentValue()
d) getAdjustmentAmount()

Answer: a
Clarification: The amount of the adjustment can be obtained from the getvalue() method, it returns an integer value corresponding to the amount of adjustment made.

8. Which of these constant value will change when the button at the end of scroll bar was clicked to increase its value?
a) BLOCK_DECREMENT
b) BLOCK_INCREMENT
c) UNIT_DECREMENT
d) UNIT_INCREMENT

Answer: d
Clarification: UNIT_INCREMENT VALUE will change when the button at the end of scroll bar was clicked to increase its value.

250+ TOP MCQs on Coding best practices and Answers

This set of Java test on “Coding best practices”.

1. What should the return type of method where there is no return value?
a) Null
b) Empty collection
c) Singleton collection
d) Empty String

Answer: b
Clarification: Returning Empty collection is a good practice. It eliminates chances of unhandled null pointer exceptions.

2. What data structure should be used when number of elements is fixed?
a) Array
b) Array list
c) Vector
d) Set

Answer: a
Clarification: Array list has variable size. Array is stored in contiguous memory. Hence, reading is faster. Also, array is memory efficient.

3. What causes the program to exit abruptly and hence its usage should be minimalistic?
a) Try
b) Finally
c) Exit
d) Catch

Answer: c
Clarification: In case of exit, the program exits abruptly hence would never be able to debug the root cause of the issue.

4. Which of the following is good coding practice to determine oddity?
i)

  1. public boolen abc(int num)
  2. {
  3. 	return num % 2 == 1;
  4. }

ii)

  1. public boolean xyz(int num)
  2. {
  3. 	return (num & 1)!= 0;
  4.  }

a) i
b) ii
c) (i) causes compilation error
d) (ii) causes compilation error

Answer: b
Clarification: Arithmetic and logical operations are much faster than division and multiplication.

5. Which one of the following causes memory leak?
a) Release database connection when querying is complete
b) Use Finally block as much as possible
c) Release instances stored in static tables
d) Not using Finally block often

Answer: d
Clarification: Finally block is called in successful as well exception scenarios. Hence, all the connections are closed properly which avoids memory leak.

6. Which of the following is a best practice to measure time taken by a process for execution?
a) System.currentTimeMillis()
b) System.nanoTime()
c) System.getCurrentTime()
d) System.getProcessingTime()

Answer: b
Clarification: System.nanoTime takes around 1/100000 th of a second whereas System.currentTimeMillis takes around 1/1000th of a second.

7. What one of the following is best practice to handle Null Pointer exception?
i) int noOfStudents = line.listStudents().count;
ii) int noOfStudents = getCountOfStudents(line);

  1.     public int getCountOfStudents(List line)
  2.     {
  3. 	if(line != null)
  4.         {
  5. 		if(line.listOfStudents() != null)
  6.                 {
  7. 			return line.listOfStudents().size();
  8. 		}
  9. 	}
  10. 	throw new NullPointerException("List is empty");
  11.     }

a) Option (i)
b) Option (ii)
c) Compilation Error
d) Option (ii) gives incorrect result

Answer: b
Clarification: Null check must be done while dealing with nested structures to avoid null pointer exceptions.

8. Which of the below is true about java class structure?
a) The class name should start with lowercase
b) The class should have thousands of lines of code
c) The class should only contain those attribute and functionality which it should; hence keeping it short
d) The class attributes and methods should be public

Answer: c
Clarification: Class name should always start with upper case and contain those attribute and functionality which it should (Single Responsibility Principle); hence keeping it short. The attributes should be usually private with get and set methods.

9. Which of the below is false about java coding?
a) variable names should be short
b) variable names should be such that they avoid ambiguity
c) test case method names should be created as english sentences without spaces
d) class constants should be used when we want to share data between class methods

Answer: a
Clarification: variable names like i, a, abc, etc should be avoided. They should be real world names which avoid ambiguity. Test case name should explain its significance.

10. Which is better in terms of performance for iterating an array?
a) for(int i=0; i<100; i++)
b) for(int i=99; i>=0; i–)
c) for(int i=100; i<0; i++)
d) for(int i=99; i>0; i++)

Answer: b
Clarification: reverse traversal of array take half number cycles as compared to forward traversal. The other for loops will go in infinite loop.

To practice all areas of Java for tests, here is complete set on Multiple Choice Questions and Answers on Java.

contest

Advanced 250+ TOP MCQs on AutoCloseable, Closeable and Flushable Interfaces and Answers

This set of Advanced Java Multiple Choice Questions & Answers (MCQs) on “AutoCloseable, Closeable and Flushable Interfaces”.

1. Autocloseable was introduced in which Java version?
a) java SE 7
b) java SE 8
c) java SE 6
d) java SE 4

Answer: a
Clarification: Java 7 introduced autocloseable interface.

2. What is the alternative of using finally to close resource?
a) catch block
b) autocloseable interface to be implemented
c) try block
d) throw Exception

Answer: b
Clarification: Autocloseable interface provides close() method to close this resource and any other underlying resources.

3. Which of the below is a child interface of Autocloseable?
a) Closeable
b) Close
c) Auto
d) Cloneable

Answer: a
Clarification: A closeable interface extends autocloseable interface. A Closeable is a source or destination of data that can be closed.

4. It is a good practise to not throw which exception in close() method of autocloseable?
a) IOException
b) CustomException
c) InterruptedException
d) CloseException

Answer: c
Clarification: InterruptedException interacts with a thread’s interrupted status and runtime misbehavior is likely to occur if an InterruptedException is suppressed.

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

  1. try (InputStream is = ...) 
  2. {
  3.     // do stuff with is...
  4. } 
  5. catch (IOException e) 
  6. {
  7.     // handle exception
  8. }

a) Runtime Error
b) IOException
c) Compilation Error
d) Runs successfully

Answer: d
Clarification: Using java 7 and above, AutoCloseable objects can be opened in the try-block (within the ()) and will be automatically closed instead of using the finally block.

6. What is the difference between AutoCloseable and Closeable?
a) Closeable is an interface and AutoCloseable is a concrete class
b) Closeable throws IOException; AutoCloseable throws Exception
c) Closeable is a concept; AutoCloseable is an implementation
d) Closeable throws Exception; AutoCloseable throws IOException

Answer: b
Clarification: Closeable extends AutoCloseable and both are interfaces. Closeable throws IOException and AutoCloseable throws Exception.

7. What is the use of Flushable interface?
a) Flushes this stream by writing any buffered output to the underlying stream
b) Flushes this stream and starts reading again
c) Flushes this connection and closes it
d) Flushes this stream and throws FlushException

Answer: a
Clarification: Flushable interface provides flush() method which Flushes this stream by writing any buffered output to the underlying stream.

8. Which version of java added Flushable interface?
a) java SE 7
b) java SE 8
c) java SE 6
d) java SE 5

Answer: d
Clarification: Flushable and Closeable interface are added in java SE 5.

9. Does close() implicitly flush() the stream.
a) True
b) False

Answer: a
Clarification: close() closes the stream but it flushes it first.

10. AutoCloseable and Flushable are part of which package?
a) Autocloseable java.lang; Flushable java.io
b) Autocloseable java.io; Flushable java.lang
c) Autocloseable and Flushable java.io
d) Autocloseable and Flushable java.lang

Answer: a
Clarification: Autocloseable is a part of java.lang; Flushable is a part of java.io.

contest