Saturday, August 10, 2024

String, StringBuffer, and StringBuilder MCQ's

 Here are multiple-choice questions (MCQs) on String, StringBuffer, and StringBuilder in Java:


Question 1

Which of the following is immutable in Java?


A) String


B) StringBuffer


C) StringBuilder


D) All of the above


Answer: A) String


Question 2

What is the key difference between StringBuffer and StringBuilder?


A) StringBuffer is immutable, while StringBuilder is mutable.


B) StringBuffer is synchronized, while StringBuilder is not.


C) StringBuffer is faster than StringBuilder.


D) There is no difference.


Answer: B) StringBuffer is synchronized, while StringBuilder is not.


Question 3

Which of the following classes is thread-safe?


A) String


B) StringBuffer


C) StringBuilder


D) None of the above


Answer: B) StringBuffer


Question 4

What is the default initial capacity of a StringBuffer or StringBuilder object?


A) 8


B) 10


C) 16


D) 32


Answer: C) 16


Question 5

Which method in String class is used to return a new string that is a substring of the original string?


A) split()


B) subString()


C) substring()


D) slice()


Answer: C) substring()


Question 6

Which of the following will create an empty StringBuilder object with a specified capacity of 50?


A) new StringBuilder();


B) new StringBuilder(50);


C) new StringBuilder("50");


D) new StringBuilder(new String("50"));


Answer: B) new StringBuilder(50);


Question 7

Which method is used to reverse the characters in a StringBuffer or StringBuilder object?


A) reverseString()


B) reverse()


C) invert()


D) flip()


Answer: B) reverse()


Question 8

Which of the following methods is NOT available in the String class?


A) append()


B) charAt()


C) length()


D) equals()


Answer: A) append()


Question 9

What will be the output of the following code?


java

Copy code

String str1 = "Hello";

String str2 = "Hello";

System.out.println(str1 == str2);

A) true


B) false


C) Compilation error


D) Runtime error


Answer: A) true


Question 10

What is the output of the following code?


java

Copy code

String str = "abc";

str.concat("def");

System.out.println(str);

A) abcdef


B) def


C) abc


D) abcdefdef


Answer: C) abc


Question 11

Which class should be used when you need a mutable sequence of characters that is not thread-safe?


A) String


B) StringBuffer


C) StringBuilder


D) CharSequence


Answer: C) StringBuilder


Question 12

What will be the output of the following code?


java

Copy code

StringBuffer sb = new StringBuffer("Hello");

sb.append(" World");

System.out.println(sb.toString());

A) Hello World


B) HelloWorld


C) Hello


D) World


Answer: A) Hello World


Question 13

Which of the following is the correct way to create a new String object from a StringBuffer object?


A) new String(new StringBuffer("Hello"));


B) new StringBuffer(new String("Hello"));


C) StringBuffer.toString();


D) new StringBuffer("Hello").toString();


Answer: D) new StringBuffer("Hello").toString();


Question 14

What is the primary purpose of the capacity() method in StringBuffer and StringBuilder?


A) To return the current length of the string.


B) To return the maximum length that the object can hold without resizing.


C) To return the number of characters in the object.


D) To return the number of unused space left in the object.


Answer: B) To return the maximum length that the object can hold without resizing.


Question 15

What is the output of the following code?


java

Copy code

StringBuilder sb = new StringBuilder("abc");

sb.delete(1, 3);

System.out.println(sb);

A) a


B) ab


C) c


D) ac


Answer: A) a


Question 16

Which of the following methods can be used to compare two strings lexicographically in Java?


A) compareTo()


B) equals()


C) compare()


D) compareWith()


Answer: A) compareTo()


Question 17

What will be the output of the following code?


java

Copy code

String str = "hello";

String upperStr = str.toUpperCase();

System.out.println(upperStr);

A) HELLO


B) hello


C) Hello


D) hELLO


Answer: A) HELLO


Question 18

Which of the following is true about the insert() method in StringBuffer and StringBuilder?


A) It replaces characters in the string.


B) It inserts characters at a specified position.


C) It appends characters to the end of the string.


D) It deletes characters from the string.


Answer: B) It inserts characters at a specified position.


Question 19

What is the purpose of the substring(int beginIndex, int endIndex) method in the String class?


A) To return a new string starting from beginIndex to endIndex.


B) To modify the original string from beginIndex to endIndex.


C) To delete a portion of the string from beginIndex to endIndex.


D) To replace the characters from beginIndex to endIndex.


Answer: A) To return a new string starting from beginIndex to endIndex.


Question 20

What will be the result of the following code?


java

Copy code

String str = "java";

StringBuilder sb = new StringBuilder(str);

str = sb.reverse().toString();

System.out.println(str);

A) avaj


B) java


C) Error


D) jvaa


Answer: A) avaj


Converting an integer to a string MCQ

 Here are multiple-choice questions (MCQs) on converting an integer to a string in Java:


Question 1

Which of the following methods can be used to convert an integer to a string in Java?


A) Integer.toString()


B) String.valueOf()


C) Integer.toString(int)


D) All of the above


Answer: D) All of the above


Question 2

What will be the output of the following code?


java

Copy code

int number = 123;

String str = Integer.toString(number);

System.out.println(str);

A) 123


B) "123"


C) Error


D) null


Answer: B) "123"


Question 3

Which method is more efficient for converting an integer to a string, String.valueOf() or Integer.toString()?


A) String.valueOf() is more efficient.


B) Integer.toString() is more efficient.


C) Both are equally efficient.


D) new String(int) is more efficient.


Answer: C) Both are equally efficient.


Question 4

What will the following code return?


java

Copy code

String str = String.valueOf(456);

A) "456"


B) 456


C) null


D) Error


Answer: A) "456"


Question 5

What does the following code do?


java

Copy code

int num = 789;

String str = "" + num;

A) Converts the integer 789 to a string "789" by concatenation.


B) Converts the integer 789 to a string "789" using String.valueOf().


C) Results in a compilation error.


D) Converts the integer 789 to a string "789" using Integer.toString().


Answer: A) Converts the integer 789 to a string "789" by concatenation.


Question 6

What is the output of the following code?


java

Copy code

int number = 0;

String str = Integer.toString(number);

System.out.println(str);

A) "0"


B) 0


C) null


D) "null"


Answer: A) "0"


Question 7

Which of the following is NOT a valid way to convert an integer to a string in Java?


A) Integer.toString(int)


B) String.valueOf(int)


C) Integer.toString()


D) "" + int


Answer: C) Integer.toString()


Question 8

What is the result of the following code?


java

Copy code

String str = Integer.toString(1234, 2);

A) "1234"


B) "1234" in binary


C) "10011010010"


D) Error


Answer: C) "10011010010"


Question 9

Can the String.valueOf() method convert an integer array to a string?


A) Yes, it converts each element to a string.


B) No, it throws an exception.


C) Yes, it converts the array's memory address to a string.


D) No, it returns "null".


Answer: C) Yes, it converts the array's memory address to a string.


Question 10

What will be the output of the following code?


java

Copy code

int num = 2147483647;

String str = Integer.toString(num);

System.out.println(str);

A) "2147483647"


B) 2147483647


C) -2147483647


D) Error


Answer: A) "2147483647"


Question 11

Which of the following can be used to convert an integer to a string with a specific radix?


A) String.valueOf(int, int)


B) Integer.toString(int, int)


C) String.valueOf(int, radix)


D) Integer.parseInt(int, int)


Answer: B) Integer.toString(int, int)


Question 12

What does the following code do?


java

Copy code

String str = String.valueOf(0);

A) Converts the integer 0 to the string "0".


B) Converts the integer 0 to the string "null".


C) Throws a NullPointerException.


D) Does not compile.


Answer: A) Converts the integer 0 to the string "0".


Question 13

What will be the output of the following code?


java

Copy code

int num = -123;

String str = Integer.toString(num);

System.out.println(str);

A) "123"


B) "-123"


C) "0"


D) Error


Answer: B) "-123"


Question 14

What is the result of Integer.toString(10, 16)?


A) "10"


B) "A"


C) "16"


D) "10" in hexadecimal


Answer: B) "A"


Question 15

Can you use String.valueOf() to convert a primitive int to a string?


A) Yes


B) No


C) Only with autoboxing


D) Only if the int is not null


Answer: A) Yes


Question 16

Which method provides more control over the conversion of an int to a string?


A) Integer.parseInt()


B) Integer.toString()


C) String.valueOf()


D) Both B and C


Answer: B) Integer.toString()


Question 17

What is the return type of Integer.toString(int)?


A) int


B) String


C) Integer


D) void


Answer: B) String


Question 18

What will the following code output?


java

Copy code

String str = Integer.toString(-32768);

System.out.println(str);

A) "32768"


B) "-32768"


C) "0"


D) Error


Answer: B) "-32768"


Question 19

Which method can be used to convert an integer to a string representation in a different number system, like binary?


A) Integer.toBinaryString(int)


B) Integer.toString(int, 2)


C) String.valueOf(int, 2)


D) A and B


Answer: D) A and B


Question 20

What happens if Integer.toString() is called with an integer value that exceeds Integer.MAX_VALUE?


A) It throws an exception.


B) It returns "2147483647".


C) It returns the string representation of Integer.MAX_VALUE.


D) This scenario is impossible; integers can't exceed Integer.MAX_VALUE.


Answer: D) This scenario is impossible; integers can't exceed Integer.MAX_VALUE.

String to an integer in Java MCQ

 converting a string to an integer in Java:

Question 1

Which method is commonly used to convert a String to an int in Java?


A) Integer.toString()


B) String.parseInt()


C) Integer.parseInt()


D) Integer.valueOfString()


Answer: C) Integer.parseInt()


Question 2

What will be the output of the following code?


java

Copy code

String str = "123";

int number = Integer.parseInt(str);

System.out.println(number);

A) 123


B) "123"


C) Error


D) 0


Answer: A) 123


Question 3

What exception is thrown if the string passed to Integer.parseInt() cannot be converted to an integer?


A) NullPointerException


B) NumberFormatException


C) IllegalArgumentException


D) ArithmeticException


Answer: B) NumberFormatException


Question 4

Which of the following code snippets correctly converts a string "456" to an integer?


A) int num = Integer.valueOf("456");


B) int num = Integer.parseInt("456");


C) int num = new Integer("456");


D) All of the above


Answer: D) All of the above


Question 5

What is the difference between Integer.parseInt() and Integer.valueOf() when converting a string to an integer?


A) Integer.parseInt() returns an Integer object, while Integer.valueOf() returns an int.


B) Integer.parseInt() returns an int, while Integer.valueOf() returns an Integer object.


C) Integer.parseInt() throws a NumberFormatException for null strings, while Integer.valueOf() does not.


D) There is no difference.


Answer: B) Integer.parseInt() returns an int, while Integer.valueOf() returns an Integer object.


Question 6

Which of the following is a valid syntax to parse a string "789" into an int using Integer.parseInt()?


A) Integer.parseInt(789);


B) Integer.parseInt("789");


C) Integer.parseInt(new String("789"));


D) B and C


Answer: D) B and C


Question 7

What will happen if the string "12.34" is passed to Integer.parseInt()?


A) It will return 12.


B) It will throw a NumberFormatException.


C) It will return 0.


D) It will return 1234.


Answer: B) It will throw a NumberFormatException.


Question 8

What will be the output of the following code?


java

Copy code

String str = null;

int number = Integer.parseInt(str);

System.out.println(number);

A) 0


B) null


C) It will throw a NullPointerException.


D) It will throw a NumberFormatException.


Answer: D) It will throw a NumberFormatException.


Question 9

Is it possible to convert a string containing only whitespace characters to an int using Integer.parseInt()?


A) Yes


B) No


C) Only if whitespace is trimmed first


D) Only for leading whitespace


Answer: B) No


Question 10

Which class in Java provides the parseInt method?


A) String


B) Integer


C) Double


D) Math


Answer: B) Integer


Question 11

What will the following code return?


java

Copy code

Integer.valueOf("010");

A) 10


B) 8


C) 2


D) It will throw a NumberFormatException.


Answer: A) 10


Question 12

Can Integer.parseInt() be used with a radix other than 10?


A) No, it always uses decimal.


B) Yes, by passing the radix as a second argument.


C) Yes, by changing the default radix.


D) No, it's only for hexadecimal.


Answer: B) Yes, by passing the radix as a second argument.


Question 13

What will the following code output?


java

Copy code

String str = "0";

int number = Integer.parseInt(str);

System.out.println(number);

A) 0


B) "0"


C) Null


D) It will throw a NumberFormatException.


Answer: A) 0


Question 14

Which method would you use to convert a string "1024" into an Integer object?


A) Integer.getInteger("1024");


B) Integer.toString("1024");


C) Integer.valueOf("1024");


D) Integer.parseInt("1024");


Answer: C) Integer.valueOf("1024");


Question 15

What will be the result of Integer.parseInt("1000", 2);?


A) 1000


B) 8


C) 16


D) It will throw a NumberFormatException.


Answer: D) It will throw a NumberFormatException.


Question 16

What will be the result of Integer.parseInt("FF", 16);?


A) 255


B) 256


C) 127


D) It will throw a NumberFormatException.


Answer: A) 255


Question 17

What will be the output of the following code?


java

Copy code

String str = "2147483648";

int number = Integer.parseInt(str);

System.out.println(number);

A) 2147483648


B) -2147483648


C) It will throw a NumberFormatException.


D) 0


Answer: C) It will throw a NumberFormatException.


Question 18

How can you convert a hexadecimal string "1A" to an integer?


A) Integer.parseInt("1A");


B) Integer.parseInt("1A", 16);


C) Integer.parseInt("1A", 10);


D) Integer.valueOf("1A", 10);


Answer: B) Integer.parseInt("1A", 16);


Question 19

Which of the following will convert the string "007" to the integer 7?


A) Integer.valueOf("007");


B) Integer.parseInt("007");


C) new Integer("007");


D) All of the above


Answer: D) All of the above


Question 20

If Integer.parseInt("abc123") is executed, what will be the result?


A) It will return 123.


B) It will return 0.


C) It will return -1.


D) It will throw a NumberFormatException.


Answer: D) It will throw a NumberFormatException.

SimpleDateFormat MCQs

 SimpleDateFormat MCQs

Which package does the SimpleDateFormat class belong to in Java?


A. java.time

B. java.util

C. java.text

D. java.lang

What is the purpose of the SimpleDateFormat class in Java?


A. To perform date arithmetic.

B. To format and parse dates in a locale-sensitive manner.

C. To convert dates to strings.

D. To store date information.

Which method is used to format a Date object into a string in a specific pattern?


A. formatDate(Date date)

B. toString(Date date)

C. toPattern(Date date)

D. format(Date date)

How do you create a SimpleDateFormat object with the pattern "dd/MM/yyyy"?


A. new SimpleDateFormat("dd-MM-yyyy")

B. new SimpleDateFormat("MM/dd/yyyy")

C. new SimpleDateFormat("dd/MM/yyyy")

D. new SimpleDateFormat("yyyy/MM/dd")

What does the pattern "yyyy-MM-dd" represent in SimpleDateFormat?


A. Day-Month-Year

B. Year-Month-Day

C. Month-Day-Year

D. Year-Day-Month

Which method in SimpleDateFormat is used to parse a string into a Date object?


A. parseDate(String source)

B. toDate(String source)

C. stringToDate(String source)

D. parse(String source)

What will be the output of the following code?


java

Copy code

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

String date = sdf.format(new Date(0));

System.out.println(date);

A. 01/01/1970

B. 31/12/1969

C. 01/01/1971

D. 02/01/1970

How do you set a specific time zone for a SimpleDateFormat object?


A. setTimeZone(TimeZone zone)

B. setZone(TimeZone zone)

C. setDefaultTimeZone(TimeZone zone)

D. setTimeZone(ZoneId zone)

Which pattern symbol represents the minute in hour in SimpleDateFormat?


A. M

B. m

C. n

D. min

What is the result of the following code?


java

Copy code

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

String date = sdf.format(new Date());

System.out.println(date);

A. Current date and time in "yyyy-MM-dd HH:mm

" format

B. Current date and time in "yyyy/MM/dd HH:mm

" format

C. Current date in "yyyy-MM-dd" format

D. Current date and time in "dd/MM/yyyy HH:mm

" format

How do you change the date format pattern of an existing SimpleDateFormat object?


A. setPattern(String pattern)

B. changePattern(String pattern)

C. applyPattern(String pattern)

D. updatePattern(String pattern)

Which pattern symbol is used for a 24-hour format of an hour in SimpleDateFormat?


A. hh

B. HH

C. kk

D. KK

What will the pattern "EEE, MMM d, ''yy" display in SimpleDateFormat?


A. Full day name, full month name, day, and full year

B. Abbreviated day name, full month name, day, and last two digits of the year

C. Abbreviated day name, full month name, day, and full year

D. Abbreviated day name, abbreviated month name, day, and last two digits of the year

Which pattern symbol is used for the day of the week in SimpleDateFormat?


A. D

B. E

C. F

D. W

What will be the output if a SimpleDateFormat object is created with the pattern "yyyy.MM.dd G 'at' HH:mm

z"?


A. Date with full year, month, day, era, time, and time zone

B. Date with year, month, day, era, time, and time zone in abbreviated form

C. Date with year, month, day, and time

D. Date with year, month, and time zone only

How do you obtain the pattern string of a SimpleDateFormat object?


A. getPattern()

B. toPattern()

C. getFormat()

D. toString()

What will the pattern "yyyy-MM-dd'T'HH:mm

.SSSXXX" display in SimpleDateFormat?


A. Date and time in ISO 8601 format

B. Date and time with time zone in ISO 8601 format

C. Date and time without milliseconds and time zone

D. Date only

Which method can you use to convert a Date object to a string using SimpleDateFormat?


A. format(Date date)

B. parse(Date date)

C. stringify(Date date)

D. toString(Date date)

What will happen if the SimpleDateFormat pattern is invalid or incorrect?


A. Throws an IllegalArgumentException

B. Returns null

C. Uses a default pattern

D. Throws a ParseException

How do you set the locale of a SimpleDateFormat object?


A. setLocale(Locale locale)

B. applyLocale(Locale locale)

C. changeLocale(Locale locale)

D. setTimeZone(Locale locale)

Answers:

C. java.text

B. To format and parse dates in a locale-sensitive manner.

D. format(Date date)

C. new SimpleDateFormat("dd/MM/yyyy")

B. Year-Month-Day

D. parse(String source)

A. 01/01/1970

A. setTimeZone(TimeZone zone)

B. m

B. Current date and time in "yyyy/MM/dd HH:mm

" format

C. applyPattern(String pattern)

B. HH

B. Abbreviated day name, full month name, day, and last two digits of the year

B. E

A. Date with full year, month, day, era, time, and time zone

B. toPattern()

A. Date and time in ISO 8601 format

A. format(Date date)

A. Throws an IllegalArgumentException

A. setLocale(Locale locale)

Date Methods MCQs

 Date Methods MCQs

Which package contains the Date class in Java?


A. java.util

B. java.sql

C. java.time

D. java.text

How do you create a Date object representing the current date and time?


A. new Date()

B. Date.getCurrentDate()

C. Date.now()

D. new Date(System.currentTimeMillis())

Which method is used to get the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by a Date object?


A. getTime()

B. getMilliseconds()

C. getEpochTime()

D. getMillis()

What does the Date method toString() return?


A. A string representation of the date in dd/MM/yyyy format.

B. The number of milliseconds since epoch.

C. A string representation of the date and time.

D. The date in yyyy-MM-dd format.

Which method sets the time represented by a Date object?


A. setTime(long time)

B. setMilliseconds(long time)

C. setDate(long time)

D. updateTime(long time)

How do you compare two Date objects to see if one is before the other?


A. compareTo(Date anotherDate)

B. isBefore(Date anotherDate)

C. before(Date anotherDate)

D. compare(Date anotherDate)

What does the Date method after(Date when) return?


A. true if the date is after the specified date.

B. true if the date is before the specified date.

C. true if the date is equal to the specified date.

D. false if the date is after the specified date.

Which method of the Date class is deprecated?


A. getDate()

B. getDay()

C. getHours()

D. All of the above

How can you set the year of a Date object to 2025?


A. setYear(2025)

B. setYear(125)

C. setYear(25)

D. setYear(2024)

Which method can be used to compare if two Date objects represent the same point in time?


A. equals(Object obj)

B. compareTo(Date anotherDate)

C. compare(Date anotherDate)

D. same(Date anotherDate)

What will the Date method before(Date when) return if the calling date is before the specified date?


A. true

B. false

C. null

D. Throws an exception

Which method in the Date class converts the date to a string of the form EEE MMM dd HH:mm:ss zzz yyyy?


A. format()

B. toString()

C. toLocaleString()

D. toGMTString()

How do you obtain the current date and time using java.util.Date?


A. Date date = new Date();

B. Date date = Date.getCurrent();

C. Date date = Date.now();

D. Date date = Date.today();

Which Date method is used to set the number of seconds after the minute, between 0 and 61?


A. setSeconds(int seconds)

B. setMinutes(int seconds)

C. setTime(int seconds)

D. setSeconds(Date date)

Which method is used to retrieve the time zone offset in hours of a Date object?


A. getTimezoneOffset()

B. getZoneOffset()

C. getOffset()

D. getTimeZone()

What is the return type of the compareTo(Date anotherDate) method?


A. boolean

B. int

C. long

D. void

How can you set the month of a Date object to February?


A. setMonth(2)

B. setMonth(1)

C. setMonth(3)

D. setMonth(0)

Which of the following methods can be used to get the day of the week from a Date object?


A. getDay()

B. getDayOfWeek()

C. getDayNumber()

D. getDayIndex()

Which method in Date is used to format the date as a string in the GMT time zone?


A. toGMTString()

B. toUTCTime()

C. toUniversalTime()

D. toGMT()

How can you set the date to the last day of the month in a Date object?


A. setDate(getLastDayOfMonth())

B. setDate(31)

C. setDate(0)

D. Manually calculate the last day and set it using setDate()

Answers:

A. java.util

A. new Date()

A. getTime()

C. A string representation of the date and time.

A. setTime(long time)

C. before(Date anotherDate)

A. true if the date is after the specified date.

D. All of the above

C. setYear(25)

A. equals(Object obj)

A. true

B. toString()

A. Date date = new Date();

A. setSeconds(int seconds)

A. getTimezoneOffset()

B. int

B. setMonth(1)

A. getDay()

A. toGMTString()

D. Manually calculate the last day and set it using setDate()

Hashtable MCQs

 Hashtable MCQs

What is a primary characteristic of a Hashtable in Java?


A. It allows null keys and values.

B. It is synchronized.

C. It maintains the order of elements.

D. It is unsynchronized.

Which method is used to add a key-value pair to a Hashtable?


A. add(key, value)

B. insert(key, value)

C. put(key, value)

D. set(key, value)

What will happen if you try to insert a null key or value into a Hashtable?


A. It will store the null key or value.

B. It will throw a NullPointerException.

C. It will store the value as an empty string.

D. It will store the key as "null".

How do you check if a specific key exists in a Hashtable?


A. hasKey(key)

B. keyExists(key)

C. containsKey(key)

D. findKey(key)

Which method removes a key-value pair from a Hashtable?


A. remove(key)

B. delete(key)

C. discard(key)

D. erase(key)

Which of the following best describes the Hashtable class in Java?


A. Allows duplicate keys

B. Allows null values

C. Synchronized

D. Maintains insertion order

What will table.get("key") return if "key" is not present in the Hashtable?


A. null

B. Throws NullPointerException

C. 0

D. An empty string

What method is used to check if a specific value exists in a Hashtable?


A. contains(value)

B. hasValue(value)

C. valueExists(value)

D. containsValue(value)

Which method provides a set view of the keys contained in a Hashtable?


A. keySet()

B. keys()

C. getKeys()

D. allKeys()

How can you clear all entries in a Hashtable?


A. clear()

B. deleteAll()

C. removeAll()

D. eraseAll()

Which method returns the number of key-value pairs in a Hashtable?


A. size()

B. count()

C. length()

D. numberOfEntries()

What happens if two different keys have the same hash code in a Hashtable?


A. Only one key-value pair is stored.

B. The second key-value pair replaces the first one.

C. Both key-value pairs are stored in a linked list at the hash index.

D. An exception is thrown.

What is the time complexity for inserting an element in a Hashtable?


A. O(1)

B. O(n)

C. O(log n)

D. O(n^2)

What will be the output of the following code?


java

Copy code

Hashtable<String, Integer> table = new Hashtable<>();

table.put("A", 1);

table.put("B", 2);

table.put("A", 3);

System.out.println(table.get("A"));

A. 1

B. 2

C. 3

D. null

What is a key difference between Hashtable and HashMap?


A. Hashtable allows null keys and values, whereas HashMap does not.

B. Hashtable is synchronized, while HashMap is not.

C. Hashtable maintains insertion order, whereas HashMap does not.

D. Hashtable is part of the java.util.concurrent package, while HashMap is not.

Which method is used to create a shallow copy of a Hashtable?


A. clone()

B. copy()

C. duplicate()

D. newInstance()

What is the default initial capacity of a Hashtable in Java?


A. 8

B. 11

C. 16

D. 20

What will table.isEmpty() return if the Hashtable contains no key-value pairs?


A. true

B. false

C. null

D. 0

Which method is used to retrieve all values in a Hashtable?


A. values()

B. allValues()

C. getValues()

D. valueSet()

What will be the result of table.containsKey("X") if the key "X" is not present in the Hashtable?


A. true

B. false

C. null

D. Throws an exception

Answers:

B. It is synchronized.

C. put(key, value)

B. It will throw a NullPointerException.

C. containsKey(key)

A. remove(key)

C. Synchronized

A. null

D. containsValue(value)

A. keySet()

A. clear()

A. size()

C. Both key-value pairs are stored in a linked list at the hash index.

A. O(1)

C. 3

B. Hashtable is synchronized, while HashMap is not.

A. clone()

B. 11

A. true

A. values()

B. false

HashMap MCQs

 HashMap MCQs

Which of the following is a characteristic of a HashMap in Java?


A. It allows duplicate keys.

B. It allows null keys and values.

C. It maintains insertion order.

D. It is synchronized.

What method is used to add a key-value pair to a HashMap?


A. put(key, value)

B. add(key, value)

C. insert(key, value)

D. append(key, value)

What does the get() method return if the specified key is not found in the HashMap?


A. Throws a NullPointerException

B. Returns null

C. Returns a default value

D. Throws a NoSuchElementException

How can you check if a HashMap contains a specific key?


A. containsKey(key)

B. hasKey(key)

C. keyExists(key)

D. findKey(key)

What will be the output of the following code?


java

Copy code

HashMap<String, Integer> map = new HashMap<>();

map.put("A", 1);

map.put("B", 2);

map.put("A", 3);

System.out.println(map.get("A"));

A. 1

B. 2

C. 3

D. null

What method is used to remove a key-value pair from a HashMap?


A. delete(key)

B. remove(key)

C. erase(key)

D. discard(key)

Which method returns the set of all keys contained in a HashMap?


A. keys()

B. keySet()

C. getKeys()

D. allKeys()

What will be the output of the following code?


java

Copy code

HashMap<String, Integer> map = new HashMap<>();

map.put("X", 10);

map.put("Y", 20);

map.put("Z", 30);

System.out.println(map.size());

A. 0

B. 1

C. 2

D. 3

What is the time complexity for accessing an element by key in a HashMap?


A. O(1)

B. O(n)

C. O(log n)

D. O(n^2)

How do you retrieve a set of all key-value pairs in a HashMap?


A. entrySet()

B. pairSet()

C. getPairs()

D. valuesSet()

What will be the result of map.containsValue(10) if the value 10 is present in the HashMap?


A. true

B. false

C. null

D. 0

What method is used to replace a value associated with a specific key in a HashMap?


A. replace(key, newValue)

B. change(key, newValue)

C. update(key, newValue)

D. modify(key, newValue)

Which of the following statements about HashMap is true?


A. HashMap maintains the order of insertion.

B. HashMap allows multiple null keys.

C. HashMap is not synchronized.

D. HashMap does not allow null values.

What will map.remove("Key") return if the key "Key" is not present in the HashMap?


A. null

B. false

C. 0

D. Throws an exception

How can you check if a HashMap is empty?


A. isEmpty()

B. empty()

C. isNull()

D. hasNoElements()

Which method returns a collection view of the values contained in a HashMap?


A. values()

B. getValues()

C. allValues()

D. valueSet()

What is the default load factor of a HashMap in Java?


A. 0.5

B. 0.75

C. 0.85

D. 1.0

What is the purpose of the computeIfAbsent method in HashMap?


A. To compute a value and add it to the map if the key is absent.

B. To compute a value if the key is present.

C. To remove a key-value pair if the key is absent.

D. To compute a new key for an absent value.

Which method can be used to create a shallow copy of a HashMap?


A. clone()

B. copy()

C. duplicate()

D. newInstance()

What will be the output of the following code?


java

Copy code

HashMap<String, String> map = new HashMap<>();

map.put("K1", "V1");

map.put("K2", "V2");

map.put("K1", "V3");

System.out.println(map.get("K1"));

A. V1

B. V2

C. V3

D. null

Answers:

B. It allows null keys and values.

A. put(key, value)

B. Returns null

A. containsKey(key)

C. 3

B. remove(key)

B. keySet()

D. 3

A. O(1)

A. entrySet()

A. true

A. replace(key, newValue)

C. HashMap is not synchronized.

A. null

A. isEmpty()

A. values()

B. 0.75

A. To compute a value and add it to the map if the key is absent.

A. clone()

C. V3

Wrapper classes in Java MCQ

 Here are multiple-choice questions (MCQs) on wrapper classes in Java:


Question 1

What is the purpose of wrapper classes in Java?


A) To wrap primitive data types into objects.


B) To handle I/O operations.


C) To manage exceptions.


D) To perform arithmetic operations.


Answer: A) To wrap primitive data types into objects.


Question 2

Which wrapper class corresponds to the primitive type int?


A) Double


B) Character


C) Integer


D) Float


Answer: C) Integer


Question 3

Which of the following is NOT a wrapper class in Java?


A) Integer


B) Double


C) Boolean


D) List


Answer: D) List


Question 4

How do you convert a primitive int to an Integer object?


A) Integer i = new Integer(10);


B) Integer i = 10;


C) Integer i = int(10);


D) Integer i = Integer.parseInt(10);


Answer: A) Integer i = new Integer(10);


Question 5

Which method of the Integer class converts a string to an integer?


A) Integer.toString()


B) Integer.parseInt()


C) Integer.valueOf()


D) Integer.convert()


Answer: B) Integer.parseInt()


Question 6

Which of the following statements is true about the Double wrapper class?


A) Double is used to wrap primitive float values.


B) Double provides methods to convert between double and String.


C) Double can only be used with double literals.


D) Double has a method called doubleValue() that returns a float.


Answer: B) Double provides methods to convert between double and String.


Question 7

Which method returns the primitive boolean value from a Boolean object?


A) booleanValue()


B) getBoolean()


C) toBoolean()


D) parseBoolean()


Answer: A) booleanValue()


Question 8

What is the default value of a wrapper class object when it is declared as a field in a class?


A) null


B) 0


C) false


D) NaN


Answer: A) null


Question 9

How do you create a Character object from a primitive char value?


A) Character c = new Character('a');


B) Character c = 'a';


C) Character c = Character.valueOf('a');


D) Character c = Character.parseChar('a');


Answer: A) Character c = new Character('a');


Question 10

Which wrapper class provides a constant for the maximum value of its type?


A) Integer


B) Boolean


C) Double


D) Character


Answer: A) Integer


Question 11

Which of the following is NOT a method provided by the Float wrapper class?


A) floatValue()


B) toString()


C) parseFloat()


D) getFloat()


Answer: D) getFloat()


Question 12

What is the result of calling Integer.parseInt("123")?


A) 123.0


B) 123


C) null


D) Integer("123")


Answer: B) 123


Question 13

How can you convert a Boolean object to a primitive boolean value?


A) Boolean.toPrimitive()


B) Boolean.getValue()


C) Boolean.booleanValue()


D) Boolean.parseBoolean()


Answer: C) Boolean.booleanValue()


Question 14

Which method of the Character class checks if a character is a digit?


A) Character.isDigit()


B) Character.isNumber()


C) Character.isDigitOrLetter()


D) Character.isNumeric()


Answer: A) Character.isDigit()


Question 15

Which wrapper class is used to represent a float data type?


A) Float


B) Double


C) Long


D) Integer


Answer: A) Float


Question 16

Which method of the Integer class returns the integer value represented by the specified string argument?


A) Integer.parseInt()


B) Integer.toInt()


C) Integer.valueOf()


D) Integer.getValue()


Answer: A) Integer.parseInt()


Question 17

Which of the following methods is used to compare two Double objects?


A) Double.compare()


B) Double.equals()


C) Double.compareTo()


D) Double.isEqual()


Answer: A) Double.compare()


Question 18

How do you obtain the primitive long value from a Long object?


A) longValue()


B) getLong()


C) toLong()


D) Long.valueOf()


Answer: A) longValue()


Question 19

What is the maximum value that can be held by an Integer wrapper class?


A) 2147483647


B) Infinity


C) 127


D) Double.MAX_VALUE


Answer: A) 2147483647


Question 20

Which wrapper class provides the method toString() to convert its value to a String?


A) Integer


B) Boolean


C) Double


D) All of the above


Answer: D) All of the above

throw and throws MCQ

Here are multiple-choice questions (MCQs) on throw and throws in Java:


Question 1

What is the purpose of the throw keyword in Java?


A) To declare that a method might throw an exception.


B) To actually throw an exception from a method or block of code.


C) To handle an exception that has been thrown.


D) To prevent exceptions from being thrown.


Answer: B) To actually throw an exception from a method or block of code.


Question 2

What does the throws keyword do in a method declaration?


A) It handles the exception that may occur.


B) It specifies the exceptions that a method may throw.


C) It rethrows an exception caught in the method.


D) It stops the execution of the method.


Answer: B) It specifies the exceptions that a method may throw.


Question 3

Which of the following statements is true about the throws keyword?


A) It is used to throw an exception immediately.


B) It must be followed by the type of exception that the method might throw.


C) It is used within a method to handle an exception.


D) It can only be used with unchecked exceptions.


Answer: B) It must be followed by the type of exception that the method might throw.


Question 4

What is the correct syntax for throwing an exception in Java?


A) throws new Exception();


B) throw new Exception();


C) throw Exception;


D) throws Exception;


Answer: B) throw new Exception();


Question 5

Consider the following method declaration:


java

Copy code

public void method() throws IOException, SQLException {

    // method implementation

}

What does this declaration indicate?


A) The method will handle IOException and SQLException.


B) The method will throw IOException and SQLException which must be handled by the caller.


C) The method will throw runtime exceptions IOException and SQLException.


D) The method will not throw any exceptions.


Answer: B) The method will throw IOException and SQLException which must be handled by the caller.


Question 6

What happens if a method with a throws clause does not handle or declare the exception specified?


A) The program will compile but may not run.


B) The method must use the throw keyword.


C) The compiler will generate an error if the exception is not handled or declared.


D) The exception will be automatically caught by the JVM.


Answer: C) The compiler will generate an error if the exception is not handled or declared.


Question 7

Which of the following correctly uses the throw keyword?


A) throws new IOException("Error occurred");


B) throw new IOException("Error occurred");


C) throws IOException("Error occurred");


D) throw IOException("Error occurred");


Answer: B) throw new IOException("Error occurred");


Question 8

If a method calls another method that throws a checked exception, what must the calling method do?


A) Catch the exception and handle it.


B) Ignore the exception.


C) Declare that it throws the exception using the throws keyword.


D) Automatically convert the exception to an unchecked exception.


Answer: C) Declare that it throws the exception using the throws keyword.


Question 9

Which of the following statements about the throw keyword is false?


A) throw is used to explicitly throw an exception.


B) The throw keyword can only be used with checked exceptions.


C) throw can be used with any type of exception, including checked and unchecked.


D) throw must be followed by an instance of Throwable or its subclasses.


Answer: B) The throw keyword can only be used with checked exceptions.


Question 10

Which keyword is used to throw an exception from within a method?


A) throws


B) throw


C) throwing


D) exception


Answer: B) throw


Question 11

In which scenario is the throws keyword used?


A) When creating a new exception object.


B) When catching exceptions inside a method.


C) When declaring exceptions that a method might throw.


D) When defining exception classes.


Answer: C) When declaring exceptions that a method might throw.


Question 12

How do you throw a checked exception from within a method?


A) By using throw keyword.


B) By declaring it in the throws clause.


C) By catching it with a try-catch block.


D) By creating an instance of Exception class.


Answer: A) By using throw keyword.


Question 13

Which of the following is an example of using throws in a method declaration?


A) public void method() throws IOException


B) public void method() throw IOException


C) public void method() { throw IOException; }


D) public void method() { throws IOException; }


Answer: A) public void method() throws IOException


Question 14

When using throws in a method signature, what must the calling code do?


A) Handle the exception using a try-catch block.


B) Ignore the exception.


C) Ensure that the exception is declared in its own method signature.


D) Use the throw keyword to handle the exception.


Answer: C) Ensure that the exception is declared in its own method signature.


Question 15

Which of the following is true about the throw keyword?


A) It can be used to handle exceptions.


B) It can only throw exceptions of type Exception.


C) It must be used to create a new instance of an exception.


D) It is used to declare that a method throws exceptions.


Answer: C) It must be used to create a new instance of an exception.


Question 16

Which keyword is used to specify multiple exceptions that a method might throw?


A) throw


B) throws


C) exception


D) catch


Answer: B) throws


Question 17

What will happen if a method that declares throws Exception is called without handling or declaring the exception?


A) The method will execute normally.


B) The program will compile and run without issues.


C) The program will not compile.


D) The exception will be handled by the JVM automatically.


Answer: C) The program will not compile.


Question 18

Which exception is thrown if the throw keyword is used incorrectly?


A) ClassNotFoundException


B) IllegalArgumentException


C) SyntaxException


D) CompileTimeException


Answer: B) IllegalArgumentException


Question 19

In which of the following scenarios is it appropriate to use throws?


A) When you want to handle an exception in the method.


B) When you want to create an instance of an exception.


C) When a method needs to propagate an exception to its caller.


D) When you want to declare that a method will not throw any exceptions.


Answer: C) When a method needs to propagate an exception to its caller.


Question 20

Which of the following is a correct example of throwing an exception and handling it?


A)


java

Copy code

public void method() throws IOException {

    throw new IOException("IO Error");

}

B)


java

Copy code

public void method() {

    throws new IOException("IO Error");

}

C)


java

Copy code

public void method() {

    throw new IOException("IO Error");

}

D)


java

Copy code

public void method() throws IOException {

    throw IOException("IO Error");

}

Answer: A) public void method() throws IOException { throw new IOException("IO Error"); }

Encapsulation MCQ

 Here are multiple-choice questions (MCQs) on encapsulation in Java:


Question 1

What is encapsulation in Java?


A) The mechanism of wrapping data and methods together in a single unit.


B) The mechanism of hiding the internal implementation and showing only the functionality.


C) The process of inheriting properties from a parent class.


D) The ability of a method or class to take on multiple forms.


Answer: A) The mechanism of wrapping data and methods together in a single unit.


Question 2

Which of the following best describes encapsulation?


A) Encapsulation is achieved using inheritance.


B) Encapsulation is achieved using polymorphism.


C) Encapsulation is achieved using access specifiers.


D) Encapsulation is achieved using abstract classes.


Answer: C) Encapsulation is achieved using access specifiers.


Question 3

In Java, how can encapsulation be implemented?


A) By using private access specifier for fields and providing public getter and setter methods.


B) By using public access specifier for fields and private getter and setter methods.


C) By using protected access specifier for fields and methods.


D) By declaring fields as final.


Answer: A) By using private access specifier for fields and providing public getter and setter methods.


Question 4

What is the purpose of getter and setter methods in Java?


A) To directly access private fields.


B) To provide controlled access to the fields.


C) To initialize the fields.


D) To perform encapsulation by making fields public.


Answer: B) To provide controlled access to the fields.


Question 5

Which access specifier is typically used for the fields in an encapsulated class?


A) public


B) private


C) protected


D) default


Answer: B) private


Question 6

What is one of the benefits of encapsulation in Java?


A) It allows modification of data directly.


B) It restricts unauthorized access to the class's data.


C) It increases the visibility of the data members.


D) It eliminates the need for constructors.


Answer: B) It restricts unauthorized access to the class's data.


Question 7

In the context of encapsulation, what does the term "data hiding" refer to?


A) Making the data members private and providing public methods to access them.


B) Making the data members public and hiding the methods.


C) Hiding the methods from the user.


D) Encrypting the data for security.


Answer: A) Making the data members private and providing public methods to access them.


Question 8

What will happen if a field in a class is declared as private?


A) It can only be accessed within the same package.


B) It can only be accessed by classes that inherit the class.


C) It cannot be accessed directly from outside the class.


D) It can be accessed from any class in the program.


Answer: C) It cannot be accessed directly from outside the class.


Question 9

Consider the following code snippet:


java

Copy code

public class Person {

    private String name;


    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }

}

What is the purpose of the getName method?


A) To change the value of the name field.


B) To retrieve the value of the name field.


C) To set the value of the name field.


D) To create a new instance of the Person class.


Answer: B) To retrieve the value of the name field.


Question 10

Which of the following is NOT a feature of encapsulation?


A) Data hiding


B) Modularity


C) Security


D) Inheritance


Answer: D) Inheritance


Question 11

What is the role of a constructor in an encapsulated class?


A) To provide methods for accessing private fields.


B) To initialize the state of an object.


C) To hide the implementation details of the class.


D) To enforce data hiding.


Answer: B) To initialize the state of an object.


Question 12

Why is encapsulation considered a good practice in Java?


A) It allows for easy modification of code.


B) It makes the code more secure and maintainable.


C) It eliminates the need for access control.


D) It automatically generates getter and setter methods.


Answer: B) It makes the code more secure and maintainable.


Question 13

Which of the following statements about encapsulation is false?


A) Encapsulation improves modularity by hiding implementation details.


B) Encapsulation allows the internal representation of an object to be hidden from the outside.


C) Encapsulation provides a clear separation between an object’s interface and its implementation.


D) Encapsulation allows data to be accessed directly, bypassing the class methods.


Answer: D) Encapsulation allows data to be accessed directly, bypassing the class methods.


Question 14

Can encapsulation prevent a class from being subclassed?


A) Yes, if the class is declared as private.


B) No, encapsulation cannot prevent subclassing.


C) Yes, if the class is declared as final.


D) Yes, if all methods are made private.


Answer: C) Yes, if the class is declared as final.


Question 15

In Java, which of the following is a common use case for encapsulation?


A) To create a singleton class.


B) To implement a method that sorts an array.


C) To control access to the fields and methods of a class.


D) To inherit methods from a superclass.


Answer: C) To control access to the fields and methods of a class.


Question 16

What is the primary benefit of encapsulating the implementation details of a class?


A) It allows the class to inherit from multiple classes.


B) It makes the class easier to use and maintain.


C) It automatically generates constructors.


D) It allows methods to be overloaded.


Answer: B) It makes the class easier to use and maintain.


Question 17

Which keyword is typically associated with encapsulation in Java?


A) interface


B) abstract


C) private


D) extends


Answer: C) private


Question 18

What happens when a field is declared as private in an encapsulated class?


A) It can only be accessed by the class in which it is defined.


B) It can be accessed by any class within the same package.


C) It can be accessed by any subclass, regardless of package.


D) It cannot be accessed by any class, including its own.


Answer: A) It can only be accessed by the class in which it is defined.


Question 19

In an encapsulated class, what is the typical way to provide read-only access to a private field?


A) By making the field public.


B) By providing a public getter method without a setter method.


C) By using the final keyword on the field.


D) By using the protected access specifier.


Answer: B) By providing a public getter method without a setter method.


Question 20

What is a typical outcome of properly implemented encapsulation?


A) A class that can be easily modified without affecting other classes.


B) A class that must expose all its fields.


C) A class that cannot be instantiated.


D) A class that does not need any constructors.


Answer: A) A class that can be easily modified without affecting other classes.

Exceptions MCQ

 MCQ 1: What is the superclass of all exceptions in Java?

A) Error

B) Throwable

C) Exception

D) RuntimeException


Answer: B) Throwable


MCQ 2: Which of the following is an unchecked exception in Java?

A) IOException

B) ClassNotFoundException

C) ArithmeticException

D) FileNotFoundException


Answer: C) ArithmeticException


MCQ 3: Which of the following keywords is used to handle exceptions in Java?

A) try

B) catch

C) finally

D) All of the above


Answer: D) All of the above


MCQ 4: What happens if an exception is not caught in a Java program?

A) The program will compile but not run.

B) The program will terminate abruptly.

C) The program will continue executing from the next line.

D) The program will skip the exception and run normally.


Answer: B) The program will terminate abruptly.


MCQ 5: Which of the following is true about the finally block?

A) It is executed only when an exception is thrown.

B) It is executed only when no exception is thrown.

C) It is executed whether or not an exception is thrown.

D) It is never executed.


Answer: C) It is executed whether or not an exception is thrown.


MCQ 6: Which of the following is a checked exception?

A) NullPointerException

B) ArrayIndexOutOfBoundsException

C) IOException

D) ArithmeticException


Answer: C) IOException


MCQ 7: What will happen if a try block does not have a corresponding catch block?

A) It will cause a compile-time error.

B) It will cause a runtime error.

C) It will cause a warning.

D) It is allowed if there is a finally block.


Answer: D) It is allowed if there is a finally block.


MCQ 8: Which of the following exceptions is thrown when a method cannot find a file that it needs to open?

A) FileNotFoundException

B) IOException

C) NullPointerException

D) EOFException


Answer: A) FileNotFoundException


MCQ 9: Which exception is thrown when an arithmetic operation results in an overflow or underflow?

A) ArithmeticException

B) IllegalArgumentException

C) IndexOutOfBoundsException

D) NumberFormatException


Answer: A) ArithmeticException


MCQ 10: What is the purpose of the throw keyword in Java?

A) To declare an exception.

B) To propagate an exception.

C) To handle an exception.

D) To manually throw an exception.


Answer: D) To manually throw an exception.



Here are multiple-choice questions (MCQs) on checked exceptions in Java:


Question 1

What is a checked exception in Java?


A) An exception that occurs due to a syntax error.


B) An exception that is checked at runtime.


C) An exception that must be either caught or declared in the method signature.


D) An exception that can be ignored during compilation.


Answer: C) An exception that must be either caught or declared in the method signature.


Question 2

Which of the following is a checked exception?


A) NullPointerException


B) ArrayIndexOutOfBoundsException


C) FileNotFoundException


D) ArithmeticException


Answer: C) FileNotFoundException


Question 3

What must a method do if it throws a checked exception?


A) Catch the exception using a try-catch block.


B) Ignore the exception.


C) Declare the exception in the method signature using the throws keyword.


D) Terminate the program.


Answer: C) Declare the exception in the method signature using the throws keyword.


Question 4

Which of the following statements about checked exceptions is true?


A) They are a type of runtime exception.


B) They are not checked at compile time.


C) They must be handled using try-catch or declared in the method signature.


D) They can be thrown without being declared.


Answer: C) They must be handled using try-catch or declared in the method signature.


Question 5

Which of the following is NOT a checked exception?


A) IOException


B) SQLException


C) ClassNotFoundException


D) RuntimeException


Answer: D) RuntimeException


Question 6

What is the primary purpose of checked exceptions in Java?


A) To handle errors that occur due to incorrect user inputs.


B) To handle unexpected errors that occur during program execution.


C) To enforce error handling for conditions that a reasonable application might want to catch.


D) To handle exceptions that are related to arithmetic operations.


Answer: C) To enforce error handling for conditions that a reasonable application might want to catch.


Question 7

Which of the following checked exceptions is thrown when an attempt is made to access a file that does not exist?


A) IOException


B) FileNotFoundException


C) IllegalArgumentException


D) SecurityException


Answer: B) FileNotFoundException


Question 8

How can a method indicate that it might throw a checked exception?


A) By including the exception in a catch block.


B) By using the throws keyword in the method signature.


C) By using the throw keyword inside the method.


D) By documenting the exception in the comments.


Answer: B) By using the throws keyword in the method signature.


Question 9

What happens if a method does not handle a checked exception and does not declare it with throws?


A) The exception is silently ignored.


B) The program will not compile.


C) The exception is automatically converted to a runtime exception.


D) The exception is thrown at runtime.


Answer: B) The program will not compile.


Question 10

Which of the following checked exceptions is related to database access?


A) SQLException


B) NullPointerException


C) ClassCastException


D) NumberFormatException


Answer: A) SQLException


Question 11

Can checked exceptions be caught by a try-catch block?


A) No, they cannot be caught.


B) Yes, they must be caught or declared in the method signature.


C) Only if they are runtime exceptions.


D) Only if they are not declared in the method signature.


Answer: B) Yes, they must be caught or declared in the method signature.


Question 12

Which exception is a subclass of Exception but not a subclass of RuntimeException?


A) IOException


B) IllegalArgumentException


C) IndexOutOfBoundsException


D) ClassCastException


Answer: A) IOException


Question 13

What keyword is used to explicitly throw an exception in Java?


A) catch


B) throw


C) throws


D) final


Answer: B) throw


Question 14

In which package are most of the checked exceptions found in Java?


A) java.util


B) java.io


C) java.lang


D) java.net


Answer: B) java.io


Question 15

Which of the following methods does not throw a checked exception?


A) Thread.sleep(long millis)


B) FileReader(String fileName)


C) Integer.parseInt(String s)


D) Class.forName(String className)


Answer: C) Integer.parseInt(String s)


Question 16

What does the throws keyword indicate in a method declaration?


A) The method can throw runtime exceptions.


B) The method must handle all exceptions internally.


C) The method can potentially throw specified checked exceptions.


D) The method does not need to handle exceptions.


Answer: C) The method can potentially throw specified checked exceptions.


Question 17

Which of the following scenarios will lead to a checked exception?


A) Dividing by zero


B) Accessing an invalid array index


C) Reading a file that does not exist


D) Converting a string to an integer


Answer: C) Reading a file that does not exist


Question 18

Can a checked exception be a superclass of RuntimeException?


A) Yes, checked exceptions are always superclasses of RuntimeException.


B) No, checked exceptions cannot be superclasses of RuntimeException.


C) Only if they are declared as final.


D) Yes, but only in custom exception classes.


Answer: B) No, checked exceptions cannot be superclasses of RuntimeException.


Question 19

What will happen if an exception is thrown by a method but not handled or declared?


A) The program will continue execution.


B) The program will ignore the exception.


C) The program will not compile.


D) The program will terminate unexpectedly at runtime.


Answer: C) The program will not compile.


Question 20

What is the role of the try block in Java?


A) To declare exceptions that might be thrown.


B) To define the code that might throw exceptions.


C) To handle exceptions that are thrown.


D) To finalize resources.


Answer: B) To define the code that might throw exceptions.




Here are multiple-choice questions (MCQs) on unchecked exceptions in Java:


Question 1

What is an unchecked exception in Java?


A) An exception that must be caught or declared in the method signature.


B) An exception that occurs due to syntax errors.


C) An exception that occurs at runtime and is not checked at compile time.


D) An exception that can only be thrown by the Java Virtual Machine (JVM).


Answer: C) An exception that occurs at runtime and is not checked at compile time.


Question 2

Which of the following is an example of an unchecked exception in Java?


A) IOException


B) SQLException


C) FileNotFoundException


D) NullPointerException


Answer: D) NullPointerException


Question 3

Which class is the superclass of all unchecked exceptions in Java?


A) Throwable


B) Exception


C) RuntimeException


D) Error


Answer: C) RuntimeException


Question 4

Which of the following exceptions is NOT an unchecked exception?


A) ArrayIndexOutOfBoundsException


B) NumberFormatException


C) ClassCastException


D) InterruptedException


Answer: D) InterruptedException


Question 5

When does a NullPointerException typically occur?


A) When an object is not found.


B) When trying to use an object reference that has the value null.


C) When accessing an out-of-bounds array index.


D) When the JVM runs out of memory.


Answer: B) When trying to use an object reference that has the value null.


Question 6

Which of the following is true about unchecked exceptions?


A) They must be handled using a try-catch block.


B) They can be caught at runtime but are not required to be declared in the method signature.


C) They are checked at compile time.


D) They must always be declared with the throws keyword.


Answer: B) They can be caught at runtime but are not required to be declared in the method signature.


Question 7

What will happen if an unchecked exception is not caught in a Java program?


A) The program will terminate immediately.


B) The exception will be ignored.


C) The program will compile but may throw an exception at runtime.


D) The program will compile and run without any issues.


Answer: C) The program will compile but may throw an exception at runtime.


Question 8

Which unchecked exception is thrown when a method receives an argument that is inappropriate?


A) IllegalArgumentException


B) IOException


C) SQLException


D) FileNotFoundException


Answer: A) IllegalArgumentException


Question 9

Can unchecked exceptions be caught using a try-catch block in Java?


A) No, unchecked exceptions cannot be caught.


B) Yes, but only if they are declared in the method signature.


C) Yes, they can be caught, but it's not mandatory.


D) Yes, but only by the JVM.


Answer: C) Yes, they can be caught, but it's not mandatory.


Question 10

Which of the following is a characteristic of unchecked exceptions?


A) They are checked at compile time.


B) They must be declared in the method signature.


C) They are caused by programming errors such as logical flaws.


D) They are primarily used for handling hardware issues.


Answer: C) They are caused by programming errors such as logical flaws.


Question 11

Which of the following unchecked exceptions occurs when an object is cast to a class of which it is not an instance?


A) ClassCastException


B) ArrayIndexOutOfBoundsException


C) ArithmeticException


D) NoSuchElementException


Answer: A) ClassCastException


Question 12

Which unchecked exception is thrown when an illegal operation is performed on a string, such as accessing an invalid index?


A) ArrayStoreException


B) StringIndexOutOfBoundsException


C) IndexOutOfBoundsException


D) ArrayIndexOutOfBoundsException


Answer: B) StringIndexOutOfBoundsException


Question 13

What does the IllegalStateException indicate in Java?


A) The program has entered an invalid state.


B) An illegal or inappropriate operation has occurred.


C) An attempt was made to access an element that does not exist.


D) A null reference was used in a method call.


Answer: A) The program has entered an invalid state.


Question 14

In Java, what is the main difference between checked and unchecked exceptions?


A) Checked exceptions are subclasses of Exception, while unchecked exceptions are subclasses of RuntimeException.


B) Unchecked exceptions must be declared in the method signature, while checked exceptions do not.


C) Checked exceptions occur at runtime, while unchecked exceptions are checked at compile time.


D) There is no difference between checked and unchecked exceptions.


Answer: A) Checked exceptions are subclasses of Exception, while unchecked exceptions are subclasses of RuntimeException.


Question 15

Which exception is thrown when an arithmetic error occurs, such as dividing by zero?


A) ArithmeticException


B) ArrayStoreException


C) NumberFormatException


D) NullPointerException


Answer: A) ArithmeticException


Question 16

Which of the following statements about unchecked exceptions is false?


A) Unchecked exceptions extend RuntimeException.


B) They can be handled using try-catch blocks.


C) They are checked by the compiler.


D) They represent programming errors that could have been prevented.


Answer: C) They are checked by the compiler.


Question 17

Which unchecked exception indicates that an operation requires a positive integer, but a negative value is provided?


A) IllegalArgumentException


B) NegativeArraySizeException


C) NumberFormatException


D) ArithmeticException


Answer: B) NegativeArraySizeException


Question 18

What does the ArrayStoreException unchecked exception indicate in Java?


A) An attempt to store the wrong type of object into an array.


B) An attempt to access an invalid array index.


C) An attempt to store a null value in an array.


D) An attempt to resize an array.


Answer: A) An attempt to store the wrong type of object into an array.


Question 19

What will be the output if the following code is executed?


java

Copy code

int[] arr = new int[5];

arr[5] = 10;

A) The value 10 is stored at the 5th index of the array.


B) A compilation error occurs.


C) An ArrayIndexOutOfBoundsException is thrown.


D) The program runs without errors.


Answer: C) An ArrayIndexOutOfBoundsException is thrown.


Question 20

Why is it not necessary to declare unchecked exceptions in a method's throws clause?


A) They are considered less important than checked exceptions.


B) They can never be caught.


C) They are typically caused by programming errors and can occur anywhere.


D) They do not have any impact on program execution.


Answer: C) They are typically caused by programming errors and can occur anywhere.


git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...