Java Strings MCQs

1 min read

In Java, strings are treated as immutable objects represented by the java.lang.String class, meaning their internal character values cannot be modified after creation. The Java runtime optimizes string creation and memory allocation using the String Constant Pool, allowing identical literal values to share memory references. Understanding the critical distinction between reference comparison (==) and content comparison (.equals()), alongside mutable alternatives like StringBuilder, is essential for writing efficient Java code and mastering technical interviews.

1. What is a String in Java?

a) A primitive data type
b) A built-in class representing a sequence of characters
c) A mutable array of characters
d) A core interface
Correct Answer: b) A built-in class representing a sequence of characters
Explanation:
In Java, String is not a primitive type. It is a class in the java.lang package that encapsulates an array of characters.

2. Which package contains the String class in Java?

a) java.util
b) java.io
c) java.lang
d) java.text
Correct Answer: c) java.lang
Explanation:
The String class is located in the java.lang package, which is automatically imported into every Java program.

3. Which of the following is true about String objects in Java?

a) They are mutable
b) They are immutable
c) They can be modified without creating a new object
d) They cannot be concatenated
Correct Answer: b) They are immutable
Explanation:
Strings in Java are immutable, meaning once a String object is created, its state or value cannot be changed.

4. Where are String literals primarily stored in Java memory?

a) Stack memory
b) String Constant Pool
c) Garbage Collector
d) Method Area exclusively
Correct Answer: b) String Constant Pool
Explanation:
To optimize memory, Java stores string literals in a special memory area called the String Constant Pool, located within the Heap.

5. How do you create a String object that is guaranteed to bypass the String Pool initially?

a) String s = 'Hello';
b) String s = new String('Hello');
c) String s = String.valueOf('Hello');
d) String s = 'Hel' + 'lo';
Correct Answer: b) String s = new String('Hello');
Explanation:
Using the new keyword forces Java to create a new String object in the main heap memory, bypassing the String Pool for the object instance.

6. What will be the output of evaluating 'Java' == 'Java' in Java?

a) false
b) true
c) Compiler error
d) NullPointerException
Correct Answer: b) true
Explanation:
Both string literals refer to the exact same object in the String Constant Pool, so the == operator evaluates to true.

7. What is the primary difference between the == operator and the equals() method when used with Strings?

a) There is no difference
b) == checks logical value equality, equals() checks memory references
c) == checks memory reference equality, equals() checks logical value equality
d) == is used for StringBuilders, equals() is for Strings
Correct Answer: c) == checks memory reference equality, equals() checks logical value equality
Explanation:
The == operator checks if two references point to the same memory location, while equals() compares the actual character sequence.

8. Which method is used to find the number of characters in a String?

a) length
b) size()
c) getSize()
d) length()
Correct Answer: d) length()
Explanation:
The length() method returns the number of characters present in the String. Unlike arrays, it is a method, not a property.

9. What is the return type of the length() method in the String class?

a) double
b) long
c) int
d) short
Correct Answer: c) int
Explanation:
The length() method returns an int representing the number of characters in the string.

10. Which method returns the character at a specified index in a String?

a) getChar()
b) charAt()
c) characterAt()
d) index()
Correct Answer: b) charAt()
Explanation:
The charAt(int index) method returns the character located at the specified index within the string.

11. In Java, String indices start at what number?

a) 1
b) 0
c) -1
d) Depends on the string size
Correct Answer: b) 0
Explanation:
Strings are backed by character arrays in Java, and array indexing always begins at 0.

12. What exception is thrown if you pass an invalid index to the charAt() method?

a) InvalidIndexException
b) StringIndexOutOfBoundsException
c) NullPointerException
d) ArrayIndexOutOfBoundsException
Correct Answer: b) StringIndexOutOfBoundsException
Explanation:
If the index is negative or greater than or equal to the string length, charAt() throws a StringIndexOutOfBoundsException.

13. Which method is explicitly used to concatenate two strings in Java without using operators?

a) add()
b) append()
c) concat()
d) merge()
Correct Answer: c) concat()
Explanation:
The concat(String str) method appends the specified string to the end of the current string.

14. What is the result of 'Hello' + 5 + 5 in Java?

a) Hello10
b) Hello55
c) Compiler Error
d) Exception at runtime
Correct Answer: b) Hello55
Explanation:
Evaluation happens from left to right. 'Hello' + 5 becomes 'Hello5', and then 'Hello5' + 5 becomes 'Hello55'.

15. What is the result of 5 + 5 + 'Hello' in Java?

a) 55Hello
b) 10Hello
c) Hello10
d) Compiler Error
Correct Answer: b) 10Hello
Explanation:
Evaluation is from left to right. 5 + 5 evaluates to 10 mathematically, then 10 + 'Hello' results in '10Hello'.

16. Which method compares two strings lexicographically based on Unicode values?

a) compare()
b) compareTo()
c) equals()
d) matches()
Correct Answer: b) compareTo()
Explanation:
The compareTo() method compares strings lexicographically based on the Unicode value of each character in the strings.

17. What does the compareTo() method return if the first string is lexicographically equal to the second string?

a) true
b) 1
c) 0
d) -1
Correct Answer: c) 0
Explanation:
If both strings are identical in content, compareTo() returns the integer 0.

18. Which method ignores case differences when comparing two strings for equality?

a) equalsIgnore()
b) equalsIgnoreCase()
c) compareIgnoreCase()
d) equalsNoCase()
Correct Answer: b) equalsIgnoreCase()
Explanation:
The equalsIgnoreCase() method compares two strings, completely ignoring the case (upper/lower) of the characters.

19. Which method is used to extract a specific part of a string?

a) sub()
b) substring()
c) split()
d) extract()
Correct Answer: b) substring()
Explanation:
The substring() method returns a new string that is a substring of the original string based on the provided indices.

20. What is the output of 'JavaProgramming'.substring(4, 11)?

a) Program
b) Programm
c) rogram
d) rogramm
Correct Answer: a) Program
Explanation:
The substring(int beginIndex, int endIndex) method includes the beginIndex (inclusive) and goes up to endIndex minus 1 (exclusive). Indices 4 to 10 are extracted, giving 'Program'.

21. Which method finds the index of the first occurrence of a specific character or substring?

a) search()
b) find()
c) indexOf()
d) positionOf()
Correct Answer: c) indexOf()
Explanation:
The indexOf() method returns the index of the first occurrence of a specified character or substring.

22. What does indexOf() return if the character is not found in the string?

a) 0
b) null
c) -1
d) Throws an exception
Correct Answer: c) -1
Explanation:
If the specified substring or character is not present in the string, indexOf() returns -1.

23. Which method finds the index of the last occurrence of a specified character?

a) lastIndexOf()
b) indexOfLast()
c) searchLast()
d) reverseIndexOf()
Correct Answer: a) lastIndexOf()
Explanation:
The lastIndexOf() method searches the string backward and returns the index of the last occurrence of the specified value.

24. Which method checks if a string begins with a particular prefix?

a) beginsWith()
b) startsWith()
c) hasPrefix()
d) firstString()
Correct Answer: b) startsWith()
Explanation:
The startsWith() method checks whether the string starts with the specified prefix, returning true or false.

25. Which method checks if a string concludes with a particular suffix?

a) concludesWith()
b) hasSuffix()
c) endsWith()
d) lastString()
Correct Answer: c) endsWith()
Explanation:
The endsWith() method evaluates if a string ends with the specified suffix, returning a boolean value.

26. What method removes leading and trailing whitespaces from a string?

a) stripWhitespace()
b) removeSpaces()
c) clean()
d) trim()
Correct Answer: d) trim()
Explanation:
The trim() method returns a copy of the string with leading and trailing whitespaces omitted.

27. Which method was introduced in Java 11 as a more advanced Unicode-aware alternative to trim()?

a) clean()
b) clear()
c) strip()
d) purge()
Correct Answer: c) strip()
Explanation:
The strip() method removes leading and trailing whitespaces and uses Character.isWhitespace() which supports Unicode whitespaces better than trim().

28. How do you convert all characters in a string to uppercase?

a) toUpperCase()
b) toUpper()
c) upperCase()
d) capsLock()
Correct Answer: a) toUpperCase()
Explanation:
The toUpperCase() method converts all of the characters in the String to uppercase using the rules of the default locale.

29. How do you convert all characters in a string to lowercase?

a) toLower()
b) toLowerCase()
c) lowerCase()
d) smallCaps()
Correct Answer: b) toLowerCase()
Explanation:
The toLowerCase() method converts all of the characters in the String to lowercase.

30. Which method replaces occurrences of a specific character in a string with a new character?

a) swap()
b) replace()
c) replaceAll()
d) change()
Correct Answer: b) replace()
Explanation:
The replace(char oldChar, char newChar) method returns a new string resulting from replacing all occurrences of oldChar in the string with newChar.

31. Which method replaces substrings using a regular expression?

a) replace()
b) replaceAll()
c) regexReplace()
d) replaceRegex()
Correct Answer: b) replaceAll()
Explanation:
The replaceAll() method replaces each substring of the string that matches the given regular expression.

32. What is the primary difference between replace() and replaceAll() in Java Strings?

a) replace() only replaces the first occurrence, replaceAll() replaces all
b) replace() takes exact character sequences, replaceAll() accepts regular expressions
c) replaceAll() only replaces characters, replace() replaces strings
d) There is no difference
Correct Answer: b) replace() takes exact character sequences, replaceAll() accepts regular expressions
Explanation:
Both methods replace all occurrences, but replaceAll() processes the target string as a Regular Expression, whereas replace() treats it as a literal sequence.

33. Which method splits a string into an array of strings based on a given delimiter?

a) divide()
b) split()
c) separate()
d) tokenize()
Correct Answer: b) split()
Explanation:
The split() method splits the string around matches of the given regular expression or delimiter and returns a String array.

34. What will 'a,b,c'.split(',') return in Java?

a) A single String 'abc'
b) A String array containing 'a', 'b', and 'c'
c) A char array containing 'a', 'b', and 'c'
d) A compilation error
Correct Answer: b) A String array containing 'a', 'b', and 'c'
Explanation:
The split method breaks the string at the specified delimiter (comma) and returns an array of strings.

35. Which method checks if a string contains a specific sequence of characters?

a) includes()
b) has()
c) contains()
d) matches()
Correct Answer: c) contains()
Explanation:
The contains() method returns true if and only if the string contains the specified sequence of char values.

36. What is the return type of the contains() method?

a) int
b) String
c) boolean
d) char
Correct Answer: c) boolean
Explanation:
The contains() method returns a boolean (true if the sequence is found, false otherwise).

37. Which method converts a String into a primitive character array?

a) toCharList()
b) getChars()
c) toCharArray()
d) asCharArray()
Correct Answer: c) toCharArray()
Explanation:
The toCharArray() method converts the string to a new character array where the array length matches the string length.

38. What does the isEmpty() method check?

a) If the string is null
b) If the string length is 0
c) If the string contains only whitespaces
d) If the string is uninitialized
Correct Answer: b) If the string length is 0
Explanation:
The isEmpty() method returns true if, and only if, the length() of the string is exactly 0.

39. Which method checks if a string is empty or contains only white space codepoints (introduced in Java 11)?

a) isEmpty()
b) isWhitespace()
c) isBlank()
d) isNull()
Correct Answer: c) isBlank()
Explanation:
The isBlank() method returns true if the string is empty or contains only whitespace codepoints.

40. What will ' '.isEmpty() return (where the string contains only three spaces)?

a) true
b) false
c) null
d) Exception
Correct Answer: b) false
Explanation:
isEmpty() strictly checks if length is 0. Since the string contains spaces, its length is 3, so it returns false.

41. What will ' '.isBlank() return (where the string contains only three spaces)?

a) true
b) false
c) null
d) Exception
Correct Answer: a) true
Explanation:
isBlank() checks if the string is empty OR contains only whitespace characters. Since it contains only spaces, it returns true.

42. How do you completely match a string against a regular expression pattern?

a) compareRegex()
b) regex()
c) matches()
d) equalsRegex()
Correct Answer: c) matches()
Explanation:
The matches() method tells whether or not this string completely matches the given regular expression.

43. Which method ensures that a string is placed into the String Constant Pool?

a) pool()
b) intern()
c) cache()
d) store()
Correct Answer: b) intern()
Explanation:
The intern() method returns a canonical representation for the string object from the String Pool.

44. Which class should you use if you need a mutable string that is thread-safe?

a) String
b) StringBuilder
c) StringBuffer
d) StringPool
Correct Answer: c) StringBuffer
Explanation:
StringBuffer provides a mutable sequence of characters and its methods are synchronized, making it thread-safe.

45. Which class should you use if you need a mutable string that is NOT thread-safe but performs faster?

a) String
b) StringBuilder
c) StringBuffer
d) CharSequence
Correct Answer: b) StringBuilder
Explanation:
StringBuilder is an unsynchronized drop-in replacement for StringBuffer, offering better performance when thread safety is not required.

46. What interface do String, StringBuffer, and StringBuilder all implement?

a) Serializable
b) CharSequence
c) Comparable
d) Iterable
Correct Answer: b) CharSequence
Explanation:
All three classes implement the CharSequence interface, which represents a readable sequence of char values.

47. If you call s.concat(' there') on a String variable s that holds 'Hi', but do not reassign it, what is the value of s?

a) Hi there
b) Hi
c) Compiler Error
d) Runtime Exception
Correct Answer: b) Hi
Explanation:
Strings are immutable. The concat() method returns a new string, but because it wasn't assigned back to the variable, the original variable remains unchanged.

48. What operator is overloaded in Java exclusively for Strings?

a) -
b) *
c) +
d) /
Correct Answer: c) +
Explanation:
The + operator is overloaded in Java specifically to support string concatenation.

49. Which method is used to reverse a sequence in the StringBuilder class?

a) invert()
b) reverse()
c) backward()
d) flip()
Correct Answer: b) reverse()
Explanation:
The StringBuilder and StringBuffer classes provide the reverse() method which reverses the internal sequence of characters.

50. Does the Java String class have a built-in reverse() method?

a) Yes
b) No, you must use StringBuilder or custom logic
c) Yes, but only in Java 11 and newer
d) No, it is called flip()
Correct Answer: b) No, you must use StringBuilder or custom logic
Explanation:
The String class does not have a reverse() method. Reversing is typically done by wrapping the String in a StringBuilder and calling reverse().

51. What is the return type of String.valueOf(int i)?

a) int
b) Integer
c) String
d) char array
Correct Answer: c) String
Explanation:
The valueOf() method converts the primitive data type (like int) into its String representation and returns a String object.

52. Which method helps to format a string using placeholders (like %s, %d)?

a) String.format()
b) String.build()
c) String.parse()
d) String.compile()
Correct Answer: a) String.format()
Explanation:
String.format() is used to create formatted strings using standard format specifiers, similar to printf in C.

53. Which class is used to concatenate strings with a specific delimiter efficiently (introduced in Java 8)?

a) StringConcat
b) StringJoiner
c) StringAppender
d) StringFormatter
Correct Answer: b) StringJoiner
Explanation:
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a suffix.

54. What static method in the String class uses a delimiter to join multiple strings (introduced in Java 8)?

a) String.combine()
b) String.merge()
c) String.join()
d) String.concatAll()
Correct Answer: c) String.join()
Explanation:
String.join() allows you to join elements of an Iterable or an array of Strings, separating them with a provided delimiter.

55. What is the result of String.join('-', 'A', 'B', 'C')?

a) ABC
b) A-B-C
c) A B C
d) -A-B-C-
Correct Answer: b) A-B-C
Explanation:
String.join() inserts the delimiter (hyphen) between the provided strings, resulting in 'A-B-C'.

56. When a String is concatenated using the + operator inside a loop in older Java versions, what happens?

a) It modifies the existing string efficiently
b) It uses a single StringBuilder under the hood
c) It creates a new StringBuilder and String object in every iteration
d) It causes a StackOverflowError
Correct Answer: c) It creates a new StringBuilder and String object in every iteration
Explanation:
In older versions of Java, using + in a loop was inefficient because it created a new StringBuilder instance and a new String for every iteration, wasting memory.

57. What does 'hello'.compareTo('hello') return?

a) 0
b) 1
c) -1
d) true
Correct Answer: a) 0
Explanation:
Since both strings are identical lexicographically, compareTo() returns exactly 0.

58. What does 'apple'.compareTo('banana') return?

a) A positive integer
b) A negative integer
c) 0
d) true
Correct Answer: b) A negative integer
Explanation:
Since 'a' comes before 'b' in the alphabet, 'apple' is lexicographically less than 'banana', returning a negative integer.

59. What happens if you call an instance method on a null String reference?

a) It returns false
b) It returns null
c) It throws a NullPointerException
d) It creates a new empty string
Correct Answer: c) It throws a NullPointerException
Explanation:
Attempting to call any instance method on a reference variable that points to null throws a NullPointerException at runtime.

60. Which of these is a correct way to instantiate an empty string?

a) String s = '';
b) String s = empty;
c) String s = null;
d) String s = void;
Correct Answer: a) String s = '';
Explanation:
An empty string literal is represented by two quotes with nothing inside. 'null' means the reference points to no object.

61. Can the String class be sub-classed (extended) in Java?

a) Yes, it is a normal class
b) No, because the String class is declared as final
c) Yes, if we implement the CharSequence interface
d) No, because it is an abstract class
Correct Answer: b) No, because the String class is declared as final
Explanation:
The String class in java.lang is marked as final, which means it cannot be inherited or sub-classed by any other class.

62. What method replaces the first occurrence of a substring that matches a given regular expression?

a) replaceOnce()
b) replaceFirst()
c) replace()
d) changeFirst()
Correct Answer: b) replaceFirst()
Explanation:
The replaceFirst() method replaces only the first substring of this string that matches the given regular expression.

63. How can you convert an integer value of 100 to the String '100' safely?

a) String s = 100;
b) String s = (String) 100;
c) String s = String.valueOf(100);
d) String s = Integer.toText(100);
Correct Answer: c) String s = String.valueOf(100);
Explanation:
String.valueOf() is a static method that safely converts primitives (like int, boolean, double) to their String representation.

64. What will be the output of 'ABC'.toLowerCase()?

a) abc
b) Abc
c) ABC
d) Compiler Error
Correct Answer: a) abc
Explanation:
The toLowerCase() method converts all uppercase letters in the string to lowercase.

65. What is the capacity of an empty StringBuffer by default?

a) 0
b) 16
c) 32
d) 10
Correct Answer: b) 16
Explanation:
When created using the default constructor, StringBuffer and StringBuilder allocate an initial capacity of 16 characters.

66. Which method in StringBuilder increases its capacity dynamically?

a) increaseCapacity()
b) ensureCapacity()
c) expandCapacity()
d) setCapacity()
Correct Answer: b) ensureCapacity()
Explanation:
The ensureCapacity() method guarantees that the internal character array is at least the specified size.

67. Which method is used to insert a string into another at a specified position using StringBuilder?

a) add()
b) append()
c) insert()
d) put()
Correct Answer: c) insert()
Explanation:
The insert() method allows you to insert a string into a StringBuilder at a specific index location.

68. Which method removes a sequence of characters from a StringBuilder?

a) remove()
b) delete()
c) clear()
d) erase()
Correct Answer: b) delete()
Explanation:
The delete() method removes characters from the StringBuilder sequence starting at the specified start index.

69. In Java 9 and newer, how are Strings primarily stored internally to save memory?

a) As UTF-16 char arrays
b) As byte arrays (Compact Strings)
c) As bit arrays
d) As int arrays
Correct Answer: b) As byte arrays (Compact Strings)
Explanation:
Starting in Java 9, the Compact Strings feature stores Strings as byte arrays with an encoding flag, instead of char arrays, to save memory for Latin-1 strings.

70. What method returns a stream of lines extracted from a string (introduced in Java 11)?

a) getLines()
b) lines()
c) stream()
d) splitLines()
Correct Answer: b) lines()
Explanation:
The lines() method returns a Stream consisting of the lines extracted from the string, separated by line terminators.

71. Which method repeats a string a given number of times (introduced in Java 11)?

a) multiply()
b) repeat()
c) copy()
d) duplicate()
Correct Answer: b) repeat()
Explanation:
The repeat() method returns a string whose value is the concatenation of this string repeated the specified number of times.

72. What will 'A'.repeat(3) output?

a) A3
b) AAA
c) A A A
d) 3A
Correct Answer: b) AAA
Explanation:
The repeat method takes the original string and concatenates it with itself 3 times.

73. Is the String class considered thread-safe in Java?

a) No, it requires manual synchronization
b) Yes, because it is immutable
c) Yes, but only if wrapped in a ThreadLocal
d) No, use StringBuffer instead
Correct Answer: b) Yes, because it is immutable
Explanation:
Because String objects are immutable, their state cannot be changed after creation, making them inherently thread-safe for reading.

74. What will be the output of calling stripLeading() on a string that has spaces on both ends?

a) Spaces removed from both ends
b) Spaces removed from the beginning only
c) Spaces removed from the end only
d) No spaces are removed
Correct Answer: b) Spaces removed from the beginning only
Explanation:
stripLeading() removes whitespace only from the beginning (left side) of the string, leaving trailing spaces intact.

75. What will be the output of calling stripTrailing() on a string that has spaces on both ends?

a) Spaces removed from both ends
b) Spaces removed from the beginning only
c) Spaces removed from the end only
d) No spaces are removed
Correct Answer: c) Spaces removed from the end only
Explanation:
stripTrailing() removes whitespace only from the end (right side) of the string, leaving leading spaces intact.

76. Which of these expressions is the safest way to compare a String variable 's' to the literal 'Hello' to avoid a NullPointerException?

a) s.equals('Hello')
b) s == 'Hello'
c) 'Hello'.equals(s)
d) s.compareTo('Hello') == 0
Correct Answer: c) 'Hello'.equals(s)
Explanation:
Invoking equals() on a known non-null literal (like 'Hello') prevents a NullPointerException, even if the variable 's' is null.

77. What does String.valueOf((Object) null) return in Java?

a) null
b) The string literal 'null'
c) NullPointerException
d) Compiler Error
Correct Answer: b) The string literal 'null'
Explanation:
Calling String.valueOf() on an object reference that is null returns the literal string 'null'. Passing a raw char array null throws an NPE.

78. If you have String s = 'hello'; why does s.length cause a compiler error?

a) Because strings do not have length
b) Because length is an array property, whereas for Strings it is a method length()
c) Because it should be size()
d) Because the string is not initialized
Correct Answer: b) Because length is an array property, whereas for Strings it is a method length()
Explanation:
In Java, length is a property for arrays, but for Strings, it is a method. You must use s.length() with parentheses.

79. Which method translates escape sequences (like a newline character) in a string literal into actual characters (Java 15+)?

a) translateEscapes()
b) parseEscapes()
c) evaluate()
d) format()
Correct Answer: a) translateEscapes()
Explanation:
Introduced in Java 15, translateEscapes() returns a string whose value is the original string with escape sequences translated as if in a string literal.

80. What feature allows you to define multi-line string literals easily in Java 15+?

a) String arrays
b) Text Blocks
c) Multiline strings
d) Raw Strings
Correct Answer: b) Text Blocks
Explanation:
Text blocks, standard in Java 15, allow multi-line string literals using triple quotes.

81. What method adjusts the indentation of each line of a string (Java 12+)?

a) indent()
b) padding()
c) shift()
d) margin()
Correct Answer: a) indent()
Explanation:
The indent(int n) method adjusts the indentation of each line of the string based on the provided integer.

82. If you call 'java'.substring(1, 1), what is the result?

a) 'j'
b) 'a'
c) An empty string
d) StringIndexOutOfBoundsException
Correct Answer: c) An empty string
Explanation:
The substring begins at index 1 and ends at index 1 (exclusive). Because beginIndex equals endIndex, it returns an empty string.

83. What is the return type of the chars() method introduced in Java 9?

a) char array
b) Stream of Characters
c) IntStream
d) List of Characters
Correct Answer: c) IntStream
Explanation:
The chars() method returns an IntStream of int zero-extending the char values from this sequence.

84. Which interface represents an object capable of storing a sequence of characters and is implemented by StringBuilder?

a) Appendable
b) Stringable
c) Writable
d) CharacterSequence
Correct Answer: a) Appendable
Explanation:
StringBuilder and StringBuffer both implement the Appendable interface, which specifies methods for appending characters or character sequences.

85. What does 'Test'.charAt(10) do?

a) Returns null
b) Returns empty char
c) Throws StringIndexOutOfBoundsException
d) Returns 't'
Correct Answer: c) Throws StringIndexOutOfBoundsException
Explanation:
Because 'Test' has a length of 4 (indices 0 to 3), asking for index 10 is out of bounds and throws an exception.

86. What is the result of 'Hello'.substring(2)?

a) He
b) ll
c) llo
d) lo
Correct Answer: c) llo
Explanation:
The overloaded substring(int beginIndex) method returns a substring starting from the given index to the end of the string.

87. Can a switch statement be used with String variables in Java?

a) No, switch only supports int and char
b) Yes, but only in Java 8 and above
c) Yes, starting from Java 7
d) No, strings must use if-else
Correct Answer: c) Yes, starting from Java 7
Explanation:
Since Java 7, the switch statement supports String objects, comparing them using the equals() method internally.

88. Which method is used to convert a String to a primitive integer?

a) Integer.toInteger()
b) Integer.parseInt()
c) String.toInt()
d) String.parseInteger()
Correct Answer: b) Integer.parseInt()
Explanation:
Integer.parseInt() parses the string argument as a signed decimal integer.

89. What exception is thrown if Integer.parseInt() fails to parse a non-numeric string?

a) ParseException
b) NumberFormatException
c) IllegalArgumentException
d) InputMismatchException
Correct Answer: b) NumberFormatException
Explanation:
If the string does not contain a parsable integer, a NumberFormatException is thrown.

90. Which is more memory efficient if you are concatenating strings in a single-threaded loop?

a) String concatenation using the + operator
b) StringBuffer
c) StringBuilder
d) String.concat()
Correct Answer: c) StringBuilder
Explanation:
StringBuilder is highly efficient for concatenation in loops and avoids the synchronization overhead present in StringBuffer.

91. What happens when you create a String using a byte array in Java?

a) Compiler error
b) It decodes the bytes into characters using a charset
c) It creates a string showing the byte addresses
d) It throws an exception
Correct Answer: b) It decodes the bytes into characters using a charset
Explanation:
The String constructor can decode a byte array into characters using the platform default charset or a specified charset.

92. Which of these is NOT a valid constructor of the String class?

a) String(char[] value)
b) String(byte[] bytes)
c) String(StringBuilder builder)
d) String(int size)
Correct Answer: d) String(int size)
Explanation:
The String class does not have a constructor that takes a single integer representing a size. Strings are dynamically sized based on their content.

93. What will 'hello'.indexOf('l', 3) return?

a) 2
b) 3
c) 4
d) -1
Correct Answer: b) 3
Explanation:
The indexOf(int ch, int fromIndex) method searches for the character starting from the specified index. The 'l' at index 3 is found.

94. What does String.copyValueOf(char[] data) do?

a) Copies the char array into a new char array
b) Returns a String that represents the character sequence in the array
c) Deep copies a String object
d) Throws a deprecation warning
Correct Answer: b) Returns a String that represents the character sequence in the array
Explanation:
copyValueOf() is a static method that returns a new String constructed from the provided character array, functionally equivalent to valueOf(char[]).

95. Which class is the direct superclass of String?

a) CharSequence
b) Object
c) Text
d) None
Correct Answer: b) Object
Explanation:
Like all classes in Java, the String class directly extends java.lang.Object.

96. What does calling trim() on a string consisting only of four spaces return?

a) A string of four spaces
b) A string of one space
c) An empty string
d) Exception
Correct Answer: c) An empty string
Explanation:
trim() removes all leading and trailing spaces. A string of only spaces becomes an empty string, which has a length of 0.

97. Why is a char array often considered more secure than a String for storing passwords?

a) String is more secure because it is immutable
b) A char array can be explicitly overwritten in memory immediately after use
c) There is no difference in security
d) String is encrypted by default
Correct Answer: b) A char array can be explicitly overwritten in memory immediately after use
Explanation:
Because Strings are immutable, their value stays in memory until garbage collected. A char array can be manually overwritten with blanks immediately after use to protect sensitive data.

98. What will 'abc'.codePointAt(0) return?

a) 'a'
b) The ASCII/Unicode integer value of 'a' (97)
c) 0
d) Exception
Correct Answer: b) The ASCII/Unicode integer value of 'a' (97)
Explanation:
codePointAt() returns the Unicode code point value (an integer) of the character at the specified index.

99. What will be the output of System.out.println(String.join('', 'J', 'a', 'v', 'a'))?

a) J,a,v,a
b) Java
c) J a v a
d) Compiler Error
Correct Answer: b) Java
Explanation:
The join method uses an empty string as a delimiter, effectively concatenating the strings seamlessly into 'Java'.

100. Which of these is the most efficient way to convert a large array of Strings into a single concatenated String?

a) Using a for-loop with the + operator
b) Using String.concat() in a loop
c) Using StringBuilder or String.join()
d) Using StringBuffer
Correct Answer: c) Using StringBuilder or String.join()
Explanation:
String.join() is internally optimized, and StringBuilder prevents the creation of multiple intermediate objects during iteration, making them the most efficient choices.

101. If you instantiate a StringBuilder with 'Java', what is its initial capacity?

a) 4
b) 16
c) 20
d) 32
Correct Answer: c) 20
Explanation:
When instantiated with a String, the initial capacity of a StringBuilder is the length of the string (4) plus the default 16, totaling 20.

102. What happens if a StringBuilder exceeds its current capacity while appending data?

a) It throws an OutOfMemoryError
b) It throws a CapacityExceededException
c) It automatically expands its capacity
d) It drops the incoming characters
Correct Answer: c) It automatically expands its capacity
Explanation:
StringBuilder dynamically reallocates a larger backing array when the appended data exceeds the current capacity.

103. What method would you use on a StringBuilder to reduce its internal array size to match exactly the sequence length?

a) shrink()
b) trimToSize()
c) compact()
d) reduceCapacity()
Correct Answer: b) trimToSize()
Explanation:
trimToSize() attempts to reduce storage used for the character sequence by trimming the internal array to exactly fit the current content.

104. Which String method applies a custom Function to the string and returns the result (introduced in Java 12)?

a) map()
b) transform()
c) apply()
d) convert()
Correct Answer: b) transform()
Explanation:
The transform(Function f) method applies the provided function to the string and returns the result. It is useful for chaining.

105. Which String method resolves formatted values into the string automatically without needing static String.format (Java 15+)?

a) formatted()
b) resolve()
c) inject()
d) fill()
Correct Answer: a) formatted()
Explanation:
The instance method formatted() acts as a convenient instance-level equivalent to the static String.format() method.

106. Is String a primitive type in Java?

a) Yes, because it can be declared directly as a literal
b) No, it is a reference type (an Object)
c) Yes, but only in newer versions of Java
d) It is a wrapper class like Integer
Correct Answer: b) No, it is a reference type (an Object)
Explanation:
Despite being widely used and supporting literals, String is a fully-fledged Class in Java, making it a reference type.

107. Why is String a popular choice as a key in a HashMap?

a) Because it implements Iterable
b) Because it is immutable, ensuring the hash code never changes once created
c) Because it has no memory limits
d) Because it inherently sorts the map
Correct Answer: b) Because it is immutable, ensuring the hash code never changes once created
Explanation:
Immutability guarantees that a string's calculated hashcode won't change, which is vital for the reliable retrieval of objects from Hash-based collections.

108. How can you safely determine if a string contains another string regardless of case?

a) str1.containsIgnoreCase(str2)
b) str1.toLowerCase().contains(str2.toLowerCase())
c) str1.matchesIgnoreCase(str2)
d) str1.has(str2)
Correct Answer: b) str1.toLowerCase().contains(str2.toLowerCase())
Explanation:
Since Java String does not have a containsIgnoreCase method, developers commonly normalize both strings to lowercase (or uppercase) before calling contains().

109. What will new char[]{'a','b'}.toString() generally return in Java?

a) ab
b) A memory address representation like [C@hashcode
c) a,b
d) Compiler Error
Correct Answer: b) A memory address representation like [C@hashcode
Explanation:
Calling toString() directly on an array object uses the default Object.toString() method, printing its memory hashcode representation, not the string content.

110. Which feature of Java helps prevent security risks (like SQL Injection) when passing string parameters?

a) String Pools
b) Immutability of Strings
c) StringBuffers
d) System.out.print()
Correct Answer: b) Immutability of Strings
Explanation:
Because strings cannot be changed, a validated string (like a database query parameter) cannot be maliciously altered by another thread or process after it passes security checks.

111. What is the primary interface that allows characters in a String to be iterated through using an IntStream (Java 9+)?

a) IntStreamable
b) CharSequence
c) StringIterable
d) Spliterator
Correct Answer: b) CharSequence
Explanation:
The chars() method, which returns an IntStream, is defined in the CharSequence interface, which String implements.

112. If you wish to compare a specific portion of a string with another string efficiently, which method is most optimized?

a) substring().equals()
b) regionMatches()
c) split()
d) contains()
Correct Answer: b) regionMatches()
Explanation:
The regionMatches() method checks if a specific region of the current string matches a specified region of another string without creating a new substring object.

113. What will 'A'.compareTo('a') return?

a) 0
b) A negative integer
c) A positive integer
d) Exception
Correct Answer: b) A negative integer
Explanation:
In Unicode/ASCII, uppercase letters come before lowercase letters ('A' is 65, 'a' is 97). Thus, 65 - 97 results in a negative integer.
← Previous: Java Operators MCQs
Next →: Java Variables & Data Types MCQs
C++ Memory Management MCQs

C++ Memory Management MCQs

Memory management in C++ empowers developers with direct control over hardware resources, primarily through the allocation and deallocation of memory…

By MCQs Generator
important java 8 features mcqs

Important Java 8 Features MCQs

Released in March 2014, Java 8 represents one of the most significant upgrades in the history of the Java programming…

By MCQs Generator
Latest Java Generics MCQs

Latest Java Generics MCQs

Java generics introduce compile-time type safety and reusability by allowing classes, interfaces, and methods to operate on parameterized types. Introduced…

By MCQs Generator