0% found this document useful (0 votes)
25 views23 pages

Java Interview: 35 String Questions

Grokking the Java Interview is a comprehensive guide aimed at helping Java developers prepare for interviews by covering advanced topics such as class loaders, enums, and string manipulation. The book includes practical examples, code snippets, and a dedicated section for frequently asked interview questions, particularly focusing on the String class. It serves as a valuable resource for mastering essential Java concepts to boost interview confidence.

Uploaded by

Nguyen Son
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views23 pages

Java Interview: 35 String Questions

Grokking the Java Interview is a comprehensive guide aimed at helping Java developers prepare for interviews by covering advanced topics such as class loaders, enums, and string manipulation. The book includes practical examples, code snippets, and a dedicated section for frequently asked interview questions, particularly focusing on the String class. It serves as a valuable resource for mastering essential Java concepts to boost interview confidence.

Uploaded by

Nguyen Son
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Grokking the Java Interview

Copyright © 2023 by JavinPaul

All rights reserved. No part of this publication may be reproduced,


distributed, or transmitted in any form or by any means, including
photocopying, recording, or other electronic or mechanical methods, without
the prior written permission of the publisher, except in the case of brief
quotations embodied in critical reviews and certain other noncommercial
uses permitted by copyright law.
Preface

W elcome to the second volume of "Grokking the Java Interview." This


book is a continuation of the first volume, which received an
overwhelming response from readers. Based on your feedback and
suggestions, we have brought to you this new edition, covering more
advanced topics.

In this book, we have included topics such as class loader, Enum, String,
HashMap, ConcurrentHashMap, Date and Time, Web Services, NIO, Socket
Programming, Inheritance, Abstract class, and Interface. These topics are
essential for any Java developer to master to ace their interviews.

We understand that Java interviews can be challenging, and preparing for


them can be overwhelming. Our aim with this book is to help you grok the
topics in-depth and ace your interviews with confidence.

In this book, we have provided a comprehensive explanation of each topic


along with practical examples, code snippets, and interview questions to help
you prepare for your interviews. We have also included a dedicated section
for frequently asked interview questions to help you assess your preparation.

We hope that this book will be a valuable resource in your Java interview
preparation journey. Let's get started and grok the Java interview together!

— iii —
CHAPTER 1:

Java String
Interview Questions

H ello Java Programmers, if you are preparing for a Java developer interview
and want to refresh your knowledge about the String class in Java, you have
come to the right place. In this chapter, I will share 35 Java String Questions for
Interviews. The String class and concept are essential in Java. There is not a single
Java program out there that does not use String objects, and that's why it's also
crucial from the interview point of view. In this chapter, I will share 35 String-
based questions from different Java interviews.

This list of Java String questions includes questions on [Link]


class as well as a string as data structure like some coding questions.

You can use this list to refresh your knowledge about String in Java and
prepare for your following Java interview.

35 Java String Concept Interview


Questions and Answers
Here is the list of 35 Java Interview questions based on concepts about the
String class in Java. You can also review this question to improve your
knowledge about this key Java class.

—1—
GROKKING THE JAVA INTERVIEW

Question 1
Why is String final in Java?
There are a couple of reasons for this, e.g., String pool, Caching, and
Performance, but Security is probably the most important reason. Given String is
used in sensitive places like specifying the host and port details, locking it for
modification prevents many Security related risks. It's one of the popular Java
interview questions.

Question 2
How does the substring method work in Java?
This returns a substring of a specified range from the original String on which
it is called. It returns a new String object because String is immutable and
can't be changed. However, prior to Java 7, it also held the reference of the
original array, which can prevent it from collecting garbage and causing a
memory leak, which is not ratified.

Question 3
What is the String pool in Java? What is the difference in the String pool
between Java 6 and 7?
It's a pool of cached String objects to minimize the number of String instances
and improve performance by sharing the same instance with multiple clients
and reducing garbage collection. Prior to Java 7, the String pool was located
on meta-space where class metadata was stored, but from JDK 7 onwards, it's
moved into heap space.

Question 4
What is the difference between "ABC".equals(str) and str?equals("ABC"),
where an str is a String object?
Though both look similar and return the same result if str is equal to "ABC,"
the real difference comes when the given String is null, i.e., str = null. In

—2—
JAVA STRING INTERVIEW QUESTIONS

that case, the first code snippet will return false, while the second code snippet
will throw NullPointerException.
This is one of the tricky Java questions, and if a candidate can answer this,
then he has good knowledge of Java fundamentals. It's also one of the several
weird tricks to avoid NullPointerException.

Question 5
Difference between str1 == str2 and [Link](str2)?

The critical difference is that the first one uses the == operator, which makes a
reference-based comparison, while the second one uses the equals() method,
which makes a content-based comparison. Since the String class overrides
equals() to perform character-based comparison

The first will return true only if both str1 and str2 point to the same object,
but the second one will return true if str1 and str2 have the same content,
even if they are different objects.

Question 6
When you execute String str = new String("abcd")? how many String
objects are created?

This is another tricky Java interview question, as many Java developers will
answer just one, but that's not true. There are two String objects created here.
The first String object is created by String literal "abcd," and the second one is
created by new String(). If you are not sure about how

Question 7
What does the intern() method of the String class do?

The intern() method of the String class puts the String on which it has called
into the String pool like [Link]() will put the String str into the pool.
Once the String is in the pool, it can be reused and improve performance.

—3—
GROKKING THE JAVA INTERVIEW

Question 8
How do you split comma-separated String in Java?
You can use either the StringTokenizer or the split() method of
[Link] class to split a comma-separated String. The split()
method is better because it also expects a regular expression and returns an
array of String which you can use or pass to a function.

Question 9
What is the difference between String and StringBuffer in Java?
The key difference between String and StringBuffer is that String is Immutable
while StringBuffer is mutable, which means you can change the content of a
StringBuffer without creating separate String objects. If you are creating string
programmatically, consider using StringBuffer for better performance as it
puts less pressure on Garbage Collector by reducing the number of temporary
objects.

Question 10
What is the difference between StringBuffer and StringBuilder in Java?
Now, this is interesting because both StringBuffer and StringBuilder represent
mutable String. This is also asked a follow-up question to the previous
question.

Anyway, the real difference is that methods of StringBuffer like append()


are synchronized, hence slow, while those of StringBuilder is not
synchronized, hence fast.

Otherwise, StringBuilder is just a copy of StringBuffer, and you can see that in
the Javadoc of the StringBuilder class as well.

—4—
JAVA STRING INTERVIEW QUESTIONS

Question 11
Write a program to reverse a String in Java without using StringBuffer.

This is a common coding problem from Java interviews. You can use
recursion or iteration to solve this problem.

Here's a simple program to reverse a String in Java without using


StringBuffer:

public class StringReverse {

public static void main(String[] args) {


String str = "Hello, world!";
String reversedStr = reverse(str);
[Link]("Reversed String: " +
reversedStr);
}

public static String reverse(String str) {


char[] chars = [Link]();
int left = 0;
int right = [Link] - 1;

while (left < right) {


char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}

return new String(chars);


}
}

In this program, we have first defined a reverse() method that takes a String
as input and returns the reversed String. We then convert the input String to a
character array using the toCharArray() method.

—5—
GROKKING THE JAVA INTERVIEW

We then use two pointers, left and right, to traverse the character array from
both ends. We swap the characters at left and right positions until we reach
the middle of the array.

Finally, we return the reversed String by creating a new String object from the
character array using the String(char[] chars) constructor.

Question 12
Write a program to replace a character from a given one in Java.
This is another coding problem based on String, but it doesn't specify whether
you can use String API. If not, then you can use the replace method of String
to solve this problem.

Here's a Java program to replace a character from a given String:

import [Link];

public class ReplaceChar {

public static void main(String[] args) {


Scanner input = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
[Link]("Enter the character to
replace: ");
char oldChar = [Link]().charAt(0);
[Link]("Enter the new character: ");
char newChar = [Link]().charAt(0);
String newStr = replaceChar(str, oldChar,
newChar);
[Link]("Modified string: " + newStr);
}

public static String replaceChar(String str, char


oldChar, char newChar) {
char[] charArray = [Link]();
for (int i = 0; i < [Link]; i++) {
if (charArray[i] == oldChar) {
charArray[i] = newChar;
}

—6—
JAVA STRING INTERVIEW QUESTIONS

}
return new String(charArray);
}
}

In this program, we first take the input String from the user using a Scanner
object. Then we take the character to be replaced and the new character as
input. The replaceChar() method takes the input String, old character, and
new character as input and return a String where the old character is replaced
with a new character.

Question 13
Can you write a Java program to count the occurrence of a given character
in String?
This problem requires using HashMap for string characters as keys and their
count as values. Once you know this trick, you can easily solve such string
coding problems. Just convert String to character array and then loop through
the array. For each character, store the character as a key and the value as 1 in
HashMap. If the key or character already exists, then increase the count by 1.

here's an example Java program to count the occurrence of a given character


in a String:

public class CharacterCount {


public static int countOccurrences(String str, char
ch) {
int count = 0;
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == ch) {
count++;
}
}
return count;
}

—7—
GROKKING THE JAVA INTERVIEW

This program defines a countOccurrences() method that takes a String


and a character as input, and returns the number of times the character
appears in the String. The main() method demonstrates how to use the
countOccurrences() method to count the number of occurrences of the
letter 'l' in the String "Hello World".

When you run this program you will see following output:

Number of occurrences of 'l' in "Hello World": 3

Question 14
Why is a char array better than a String for storing sensitive information?

This is one of the trick questions from Java interviews. The reason is that
because String is immutable, they are cached in memory, and there is a
good chance that they will remain in memory for a longer duration posing a
possible threat, while character array gives you the option to erase data once
they are used. This is the primary reason, but there are some more subtle
reasons.

Question 15
How to check if a String contains only numeric digits?

This is one of the simple problem to solve. You can either use a regular
expression to check if a string contains only numbers, or you can convert it to
a character array and then check the ASCII value of those characters to see if
they are in the range of numbers. For example, You can use the matches()
method in Java with a regular expression to check if a String contains only
numeric digits as shown below:

public static boolean containsOnlyDigits(String str) {

—8—
JAVA STRING INTERVIEW QUESTIONS

return [Link]("\\d+");
}

This method takes a String as input and returns a boolean indicating whether
the String contains only numeric digits or not. The regular expression \\d+
matches one or more digits. The matches() method returns true if the String
matches the regular expression and false otherwise.

Question 16
Can you write a program to check if a String is a palindrome in Java?
If you don't know, a string is said to be a palindrome if it's equal to its reverse.
In order to check if a given String is a palindrome or not, you need to first
reverse it and then compare the reversed string with the original string. If they
are equal, the given String is a palindrome. If you remember, we have seen
questions about reversing a string, you can either use that technique to
reverse a string, or you can use convert the String to StringBuffer and use its
reverse() method to reverse the given string.

Here's a Java program to check if a given string is a palindrome or not:

import [Link];

public class Palindrome {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
if(isPalindrome(str)){
[Link](str + " is a palindrome.");
} else {
[Link](str + " is not a palindrome.");
}
}

public static boolean isPalindrome(String str){

—9—
GROKKING THE JAVA INTERVIEW

int len = [Link]();


for(int i=0; i<len/2; i++){
if([Link](i) != [Link](len-i-1)){
return false;
}
}
return true;
}
}

In the above program, we first take input string from the user using Scanner.
Then, we check if the string is palindrome or not using isPalindrome()
method. This method takes a string as input and returns a boolean value true
if the string is a palindrome; otherwise false. To check if the string is
palindrome, we compare the characters from start and end of the string and
return false as soon as we find a mismatch. If we reach the middle of the
string without finding any mismatch, we return true.

Question 17
How to format String in Java?
You can use the format() method of the [Link] class to
format a given String in Java. If you just want to print the formatted String,
you can also use the [Link]() method, which prints the
formatted string to the console.

Question 18
How to convert Enum to String in Java?
Similar to any Java object, you can also use the toString() method to
convert an Enum to a String in Java. The Enum class provides a
toString() method which can be overridden by your Enum
implementations.

— 10 —
JAVA STRING INTERVIEW QUESTIONS

Question 19
How to convert String to Date in Java?
Prior to Java 8, you could use DateFormat or SimpleDateFormat class to convert
a String to Date In Java or vice-versa. From Java 8 onwards, when you use the
new Date and Time API, you can also use the DateTimeFormatter class to
convert String to LocalDate, LocalTime, or LocalDateTime class in
Java.

Question 20
Is String thread-safe in Java? Why?
Yes, String is thread-safe because it's Immutable. All Immutable objects are
thread-safe because once they are created, they can't be modified. Hence is no
issue with respect to multiple threads accessing them.

Question 21
Can we use String as the HashMap key in Java?
Yes, we can use String as a key in HashMap because it implements the
equals() and hashcode() method, which is required for an object to be
used as a key in HashMap.

Question 22
How to check if a String is empty in Java?
There are many ways to check if a String is empty in Java, e.g., you can check
its length. If the length of the String is zero, then it's empty. Otherwise, you
can also use the isEmpty() method, which returns true if the String is
empty. Though you need to be careful with requirements, e.g., a String may
contain a whitespace that will look empty, but the length will not be zero. So,
it depends upon your requirements.

— 11 —
GROKKING THE JAVA INTERVIEW

Question 23
How to convert String to int in Java?
There are many ways to convert the String to the int primitive in Java, but the
best way is by using [Link]() method. This method parses
the given string and returns a primitive int value. If you need a wrapper class
Integer object, you can use [Link]() method. Although it
internally uses the parseInt() method, it caches frequently used Integer
values, e.g., -128 to 127, which can reduce temporary objects.

Question 24
How does String concatenation using the + operator work in Java?
The + operator can be used to concatenate two Strings in Java. This is the only
operator that is overloaded, i.e., it can be used two add numbers as well as to
concatenate String. Internally, the concatenation is done by using
StringBuffer, or StringBuilder append() method, depending upon
which version of Java you are using.

Question 25
Can we use String in switch case in Java?
Yes, after the JDK 7 release, you can use the String in the switch case in Java.
Earlier, it wasn't possible, but now it's possible.

Question 26
What is the String enum pattern in Java?
This is a common pattern to declare String constants inside an enum. For
example, days of the Week can be declared as Enum so that you can use them
as Enum instead of String.

— 12 —
JAVA STRING INTERVIEW QUESTIONS

Question 27
Write a Java program to print all permutations of a String.
This is also one of the most popular string coding problems, which can be
easily solved using recursion, provided you know the permutations.

Here is a Java program to print all permutations of a String using recursion:

import [Link].*;

public class StringPermutations {

public static void main(String[] args) {


String str = "ABC";
List<String> permutations = getPermutations(str);
[Link]("Permutations of " + str + ":
" + permutations);
}

public static List<String> getPermutations(String


str) {
List<String> permutations = new ArrayList<>();
if (str == null || [Link]() == 0) {
return permutations;
}
getPermutations([Link](), 0,
permutations);
return permutations;
}

private static void getPermutations(char[] str, int


index, List<String> permutations) {
if (index == [Link] - 1) {
[Link](new String(str));
} else {
for (int i = index; i < [Link]; i++) {
swap(str, index, i);
getPermutations(str, index + 1,
permutations);
swap(str, index, i);
}
}
}

— 13 —
GROKKING THE JAVA INTERVIEW

private static void swap(char[] str, int i, int j) {


char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}

This program uses recursion to generate all possible permutations of the


input String. It first checks if the String is null or empty, and if so, returns an
empty list. Otherwise, it calls a helper function that takes in the String as a
character array, an index representing the current position in the array, and a
list to store the permutations.

If the index is at the end of the array, the function adds the current
permutation to the list. Otherwise, it swaps the current character with every
character to its right and recursively generates permutations for the
remaining characters. After each recursive call, it swaps the characters back to
their original positions to backtrack and generate the next permutation.

Question 28
What is the difference between String in C and Java?
Even though both C and Java String is backed by character array, C String is a
NULL-terminated character array while Java String is an object. This means
you can call methods on Java String, e.g., length, toUpperCase,
toLowerCase, substring, etc.

Question 29
How to convert String to double in Java?

Similar to [Link]() method, which is used to convert a


String to int, you can also use the [Link]() method to
convert a String to a double primitive value.

— 14 —
JAVA STRING INTERVIEW QUESTIONS

Question 30
How to convert String to long in Java?

It's similar to converting String to int or String to double in Java. All you need
to do is just use the parseLong() method of the Long class. This method
returns a primitive long value. Even though you can use the
[Link]() method, which can be used to convert String to Long
but it returns a Long object. Hence you would need to use auto-boxing to
convert the wrapper object to a primitive value.

Question 31
What is the difference between the format() and printf() methods in Java?

Even though both methods can be used to format Strings and they have the
same rules, the key difference is that format() method returns a formatted
String while the printf() method prints a formatted String to the console.
So, if you need a formatted String, use the format method, and if you want to
print, then use the printf() method.

Question 32
How do you append a leading zero to a numeric String?

You can use the format() method of String to append leading zeros to a
numeric String in Java.

Question 33
How to remove white space from String in Java?

You can use the trim() method to remove white space from String in Java.
It's similar to SQL Servers LTRIM() and RTRIM() methods.

— 15 —
GROKKING THE JAVA INTERVIEW

Question 34
How to check if two Strings are Anagram in Java?

There are multiple ways to solve this problem. One way is to sort both strings
and then compare them. This way, all characters will come into the same
place, and if Strings are anagrams, then they will be equal to each other.

Here's a Java program to check if two strings are anagrams or not:

import [Link];

public class AnagramChecker {

public static boolean areAnagrams(String str1, String


str2) {
// If lengths of both strings are not equal, they
cannot be anagrams
if ([Link]() != [Link]()) {
return false;
}

// Convert strings to char arrays, sort them, and


compare
char[] arr1 = [Link]();
char[] arr2 = [Link]();
[Link](arr1);
[Link](arr2);
return [Link](arr1, arr2);
}

public static void main(String[] args) {


String str1 = "listen";
String str2 = "silent";

if (areAnagrams(str1, str2)) {

— 16 —
JAVA STRING INTERVIEW QUESTIONS

[Link](str1 + " and " + str2 + "


are anagrams.");
} else {
[Link](str1 + " and " + str2 + "
are not anagrams.");
}
}
}

The program takes two strings as input and returns true if they are anagrams
of each other and false otherwise. It first checks if the lengths of the strings
are equal since if they're not, they cannot be anagrams. Then it converts both
strings to char arrays, sorts them, and checks if they are equal using the
[Link]() method. If the char arrays are equal, the strings are anagrams

Question 35
What is character encoding? What is the difference between UTF-8 and
UTF-16?

Character encoding is an algorithm that represents a character using bytes.


The UTF-8 character encoding uses 1 byte or 8 bits to represent a character of
UTF-16 uses 2 bytes or 16 bits to represent a character. They come into the
picture when you convert raw bytes to characters or strings in Java.

That's all about the top 35 Java String Interview Questions. These questions
are not only good for preparing for Java job interviews but also expand your
knowledge about String in Java, one of the key classes of JDKD. Even after
programming in Java for more than 20 years, I still discover things about core
classes that I should have known earlier. Truly, there is so much to learn in
Java.

— 17 —
— 18 —

You might also like