Java interview questions on strings

Strings in Java are immutable, meaning once they are created, their values cannot be changed. If you plan to modify text frequently, String should not be used, as it creates new objects instead of modifying existing ones. Instead,StringBuffer orStringBuilder should be used for efficient string manipulation.

For effective string handling, this guide provides an introduction to common Java string interview questions, covering topics from beginner to advanced levels with explanations and example code.

1. Basics of Strings in Java

1. What is a String in Java?

A String is a sequence of characters. In Java, strings are objects of the String class, which is part of the java.lang package. Strings are immutable, meaning their values cannot be changed once created.

Example:

String str = "Hello, World!";
2. How do you create a String in Java?

A string in Java can be created in two ways:

  1. String Literal: Created using double quotes.
  2. Using the new Keyword: Created using the new operator.

Example:

// Method 1: String Literal
String str1 = "Hello";

// Method 2: Using new Keyword
String str2 = new String("Hello");
3. What is the difference between String, StringBuilder, and StringBuffer?
  • String: Immutable and thread-safe.
  • StringBuilder: Mutable and not thread-safe.
  • StringBuffer: Mutable and thread-safe.

Example:

String str = "Hello";
StringBuilder sb = new StringBuilder("Hello");
StringBuffer sbf = new StringBuffer("Hello");
4. How do you find the length of a String?

Use the length() method of the String class.

Example:

String str = "Hello";
System.out.println(str.length()); // Output: 5

2. String Manipulation

5. How do you reverse a String in Java?

You can reverse a String using StringBuilder or by iterating through the characters.

Example:

// Using StringBuilder
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: olleH
6. How do you check if a String is a palindrome?

A palindrome is a string that reads the same forward and backward.

Example:

public static boolean isPalindrome(String str) {
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        if (str.charAt(left) != str.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}
7. How do you remove whitespace from a String?

Use the replaceAll() method with a regular expression.

Example:

String str = " Hello, World! ";
String trimmed = str.replaceAll("\\s", "");
System.out.println(trimmed); // Output: Hello,World!

3. String Comparison

8. How do you compare two Strings in Java?

Use the equals() method for content comparison and == for reference comparison.

Example:

String str1 = "Hello";
String str2 = new String("Hello");
System.out.println(str1.equals(str2)); // Output: true (content comparison)
System.out.println(str1 == str2); // Output: false (reference comparison)
9. What is the difference between equals() and equalsIgnoreCase()?
  • equals(): Compares two strings for an exact content match.
  • equalsIgnoreCase(): Compares two strings ignoring case differences.

Example:

String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.equals(str2)); // Output: false
System.out.println(str1.equalsIgnoreCase(str2)); // Output: true

4. String Conversion

10. How do you convert a String to an integer?

Use the Integer.parseInt() method.

Example:

String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // Output: 123
11. How do you convert an integer to a String?

Use theInteger.toString() method or concatenation with an empty string.

Example:

int num = 123;
String str1 = Integer.toString(num);
String str2 = "" + num;
System.out.println(str1); // Output: 123
System.out.println(str2); // Output: 123
12. How do you convert a String to a character array?

Use the toCharArray() method.

Example:

String str = "Hello";
char[] charArray = str.toCharArray();
for (char c : charArray) {
    System.out.println(c);
}

5. Advanced String Questions

13. How do you find the first non-repeated character in a String?

Use aLinkedHashMap to maintain the order of characters and count their occurrences.

Example:

import java.util.LinkedHashMap;
import java.util.Map;

public static char firstNonRepeatedChar(String str) {
    Map<Character, Integer> map = new LinkedHashMap<>();
    for (char c : str.toCharArray()) {
        map.put(c, map.getOrDefault(c, 0) + 1);
    }
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        if (entry.getValue() == 1) {
            return entry.getKey();
        }
    }
    return '\0'; // No non-repeated character found
}
14. How do you count the number of words in a String?

Split the string by spaces and count the resulting array's length.

Example:

public static int countWords(String str) {
    if (str == null || str.isEmpty()) {
        return 0;
    }
    String[] words = str.split("\\s+");
    return words.length;
}


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu