Interview Questions

What is the difference between String and StringBuilder in Java?

  • String is an immutable class, meaning its value cannot be changed once created. Any modification to a String results in the creation of a new String object.

  • StringBuilder is a mutable class that allows efficient modification of strings. It provides methods to append, insert, delete, and replace characters within a string without creating new objects.

Java Example - String:

String str = "Hello";
str = str + " World";

In this example, concatenating the string " World" to the existing str creates a new String object, resulting in memory overhead.

Java Example - StringBuilder:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");

In this example, the StringBuilder allows efficient modification of the string by appending " World" to the existing sb an object without creating new objects.

How can you concatenate strings in Java?

In Java, strings can be concatenated using the + operator or by using the concat() method.

Java Example - Using + operator:

String str1 = "Hello";
String str2 = " World";
String result = str1 + str2;

Java Example - Using concat() method:

String str1 = "Hello";
String str2 = " World";
String result = str1.concat(str2);

Both examples yield the same result, "Hello World", by concatenating the strings.

How can you split a string into an array of substrings in Java?

In Java, you can split a string into an array of substrings using the split() method, specifying a delimiter.

Java Example:

String str = "Hello,World,Java";
String[] arr = str.split(",");

In this example, the split() method splits the string str using the comma (",") delimiter, resulting in an array arr containing three substrings: "Hello", "World", and "Java".

How can you replace characters in a string in Java?

To replace characters in a string, you can use the replace() method or the replaceAll() method in Java.

Java Example - Using replace() method:

String str = "Hello, World!";
String replacedStr = str.replace("o", "X");

In this example, the replace() method replaces all occurrences of "o" with "X" in the string str, resulting in "HellX, WXXrld!".

Java Example - Using replaceAll() method:

String str = "Hello, World!";
String replacedStr = str.replaceAll("[aeiou]", "*");

In this example, the replaceAll() method replaces all lowercase vowels (a, e, i, o, u) with "", resulting in "Hll*, W*rld!".

How can you convert a string to uppercase or lowercase in Java?

To convert a string to uppercase or lowercase, you can use the toUpperCase() method or the toLowerCase() method in Java.

Java Example - Converting to uppercase:

String str = "Hello, World!";
String upperCaseStr = str.toUpperCase();

In this example, the toUpperCase() method converts all characters in the string str to uppercase, resulting in "HEL

LO, WORLD!".

Java Example - Converting to lowercase:

String str = "Hello, World!";
String lowerCaseStr = str.toLowerCase();

In this example, the toLowerCase() method converts all characters in the string str to lowercase, resulting in "hello, world!".

How can you extract a substring from a string in Java?

To extract a substring from a string, you can use the substring() method in Java, specifying the starting index and optionally the ending index.

Java Example:

String str = "Hello, World!";
String substring = str.substring(7, 12);

In this example, the substring() method extracts the substring starting from index 7 (inclusive) to index 12 (exclusive) from the string str, resulting in "World".

How can you check if a string contains a specific substring in Java?

To check if a string contains a specific substring, you can use the contains() method in Java.

Java Example:

String str = "Hello, World!";
boolean containsSubstring = str.contains("World");

In this example, the contains() method checks if the string str contains the substring "World". If the substring is found, it returns true; otherwise, it returns false.

How can you remove leading and trailing whitespaces from a string in Java?

To remove leading and trailing whitespaces from a string, you can use the trim() method in Java.

Java Example:

String str = "   Hello, World!   ";
String trimmedStr = str.trim();

In this example, the trim() method removes the leading and trailing whitespaces from the string str, resulting in "Hello, World!".

How can you check if two strings are equal in Java?

To check if two strings are equal in Java, you can use the equals() method or the equalsIgnoreCase() method for case-insensitive comparison.

Java Example - Using equals() method:

String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2);

In this example, the equals() method compares the contents of str1 and str2 and returns true if they are equal.

Java Example - Using equalsIgnoreCase() method:

String str1 = "Hello";
String str2 = "hello";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);

In this example, the equalsIgnoreCase() method compares the contents of str1 and str2 in a case-insensitive manner and returns true if they are equal.

How can you reverse a string in Java?

Java Example:

public String reverse(String str){
   String reversed = "";
   for (int i = str.length() - 1 ; i >= 0; i--) {
       reversed += str.charAt(i);
   }
   return reversed;
}

How can you check if a string is empty or null in Java?

To check if a string is empty or null in Java, you can use the isEmpty() method in combination with null check.

Java Example:

String str = ""; // or str = null;
boolean isNullOrEmpty = (str == null || str.isEmpty());

In this example, the isEmpty() method checks if the string str is empty, and the null check ensures that the string is not null. If the string is either empty or null, the isNullOrEmpty variable is set to true.

How can you count the occurrences of a specific character in a string in Java?

To count the occurrences of a specific character in a string, you can iterate through the string and compare each character with the target character.

Java Example:

String str = "Hello, World!";
char targetChar = 'o';
int count = 0;

for (char c : str.toCharArray()) {
    if (c == targetChar) {
        count++;
    }
}

In this example, the loop iterates through each character in the string str and increments the count variable whenever the target character 'o' is found.

How can you check if a string is a palindrome in Java?

To check if a string is a palindrome, you can compare the string with its reverse using the StringBuilder class.

Java Example:

String str = "madam";
StringBuilder reversedStr = new StringBuilder(str).reverse();
boolean isPalindrome = str.equals(reversedStr.toString());

In this example, the equals() method compares the original string str with its reversed version reversedStr. If they are equal, the isPalindrome variable is set to true.

How can you remove all occurrences of a specific character from a string in Java?

To remove all occurrences of a specific character from a string, you can use the replace() method.

Java Example:

String str = "Hello, World!";
char targetChar = 'o';
String removedStr = str.replace(String.valueOf(targetChar), "");

In this example, the replace() method replaces all occurrences of the target character 'o' with an empty string, effectively removing them from the original string.

How can you check if a string starts with a specific prefix in Java?

To check if a string starts with a specific prefix, you can use the startsWith() method.

Java Example:

String str = "Hello, World!";
String prefix = "Hello";
boolean startsWithPrefix = str.startsWith(prefix);

In this example, the startsWith() method checks if the string str starts with the prefix "Hello". If it does, the startsWithPrefix variable is set to true.

How can you split a string into an array of substrings in Java?

To split a string into an array of substrings, you can use the split() method.

Java Example:

String str = "Hello, World!";
String[] substrings = str.split(", ");

In this example, the split() method splits the string str into an array of substrings using the delimiter ", ", resulting in ["Hello", "World!"].

How can you convert an integer to a string in Java?

To convert an integer to a string, you can use the Integer.toString() method or the String.valueOf() method.

Java Example - Using Integer.toString():

int number = 42;
String str = Integer.toString(number);

In this example, the toString() method converts the integer number to a string.

Java Example - Using String.valueOf():

int number = 42;
String str = String.valueOf(number);

In this example, the valueOf() method converts the integer number to a string.

How to find any letter like all ‘e’ from the United States of America or from any String?

Sure, here is the Java code to find all occurrences of the letter e in the string "United States of America":

public class FindAllE {

  public static void main(String[] args) {
    String string = "United States of America";
    int count = 0;
    for (int i = 0; i < string.length(); i++) {
      if (string.charAt(i) == 'e') {
        System.out.println(string.charAt(i) + " :: " + count);
        System.out.println("index of e :: " + i);
        count++;
      }
    }
  }
}

This code will print the following output:

Code snippet

e :: 0
index of e :: 4
e :: 1
index of e :: 11
e :: 2
index of e :: 19

The code works by first creating a string called string. This string is initialized to the value "United States of America". Then, a counter variable is created to keep track of the number of occurrences of the letter e. Then, a for loop is used to iterate through the string, one character at a time. If the current character is equal to the letter e, the code prints the character and its index in the string. The code then increments the counter variable.

The main function of the code simply calls the main() method. The main() method then prints the list of all occurrences of the letter e in the string.

How to reverse the United States of America or reverse any string?

Sure, here is the Java code to reverse the string "United States of America":

Java

public class ReverseString {

  public static void main(String[] args) {
    String string = "United States of America";
    String newString = "";
    for (int i = string.length() - 1; i >= 0; i--) {
      newString += string.charAt(i);
    }
    System.out.println(newString);
  }
}

This code will print the following output:

Code snippet

aciremA fo setatS detinU

How to split the string "United States of America" into 4 pieces

public class SplitString {

  public static void main(String[] args) {
    String string = "United States of America";
    String[] words = string.split(" ");
    for (int i = 0; i < words.length; i++) {
      System.out.println(words[i]);
    }
  }
}

This code will print the following output:

Code snippet

United
States
of
America

The code works by first creating a string called string. This string is initialized to the value "United States of America". Then, a call is made to the split() method on the string object. The split() method takes a delimiter as input and returns an array of strings. In this case, the delimiter is a space character. The split() method returns an array of strings, each of which is one of the words in the original string.

Finally, a for loop is used to iterate through the array of strings and print each string.

To loop an array in Java, you can use a for loop. The syntax for a for loop to loop an array is as follows:

for (int i = 0; i < array.length; i++) {
  // Do something with the element at index i
}

In this syntax, array is the name of the array, i is a loop variable, and array.length is the length of the array. The loop will iterate through the array, one element at a time. The loop variable i will be incremented by 1 after each iteration.

How to find out which number contains 3 from 10 to 30?

public class FindNumbersWithThree {

  public static void main(String[] args) {
    for (int i = 10; i <= 30; i++) {
      if (String.valueOf(i).contains("3")) {
        System.out.println(i);
      }
    }
  }
}

This code will print the following output:

Code snippet

13
23
30

The code works by first creating a for loop that iterates from 10 to 30. Inside the loop, the String.valueOf() method is used to convert the integer i to a string. Then, the contains() method is used to check if the string contains the character "3". If the string contains the character "3", the number i is printed.

🎙️ Interviewer: What will be the output of the following program? 🤔

public static void main(String[] args) {
    String s1 = new String("pankaj");
    String s2 = new String("PANKAJ");
    System.out.println(s1 = s2);
}

🙋‍♂️ Interviewee: The output of the program will be "PANKAJ" because we are assigning the value of s2 to s1 using the assignment operator =. This program is not comparing the strings using the equality operator ==, so the case difference between the two strings does not matter in this case. 😊

🎙️ Interviewer: What will be the output of the following program? 🤔

public static void main(String[] args) {
    String s1 = new String("pankaj");
    String s2 = new String("PANKAJ");
    s2.intern();
    System.out.println(s1 == s2);
}

🙋‍♂️ Interviewee: The output of the program will be false. Although the intern() method is called on s2, which returns the reference to the string from the string pool, the reference is not assigned back to s2 in this case. Therefore, s1 and s2 still have different references, resulting in the comparison s1 == s2 evaluating to false.

If we change the code on line 3 to s2 = s2.intern();, then the output will be true because s2 will now refer to the string from the string pool, making s1 and s2 refer to the same object in memory.

Last updated