Skip to main content

Command Palette

Search for a command to run...

JAVA-00-String

Updated
•8 min read•View as Markdown

1️⃣ Java String Overview

In Java, a String is an object that represents a sequence of characters.

String str = "Hello World";  // String literal (stored in String Pool)
String str2 = new String("Hello");  // Using 'new' keyword (stored in heap)

Key Points:

  • Strings are immutable: once created, they cannot be changed.

  • Stored in String Pool (for literals) to save memory.

  • String is final → cannot be subclassed.


2️⃣ Creating Strings

String s1 = "Hello";          // String literal
String s2 = new String("Hi"); // Using constructor
char[] arr = {'J','a','v','a'};
String s3 = new String(arr);  // From char array

3️⃣ Common String Methods

MethodDescriptionExample
length()Returns string length"Hello".length() → 5
charAt(int index)Returns character at index"Hello".charAt(1) → 'e'
substring(int begin, int end)Returns substring"Hello".substring(1,4) → "ell"
contains(CharSequence s)Checks substring"Hello".contains("ell") → true
equals(String s)Compares content"Hello".equals("hello") → false
equalsIgnoreCase(String s)Ignores case"Hello".equalsIgnoreCase("hello") → true
trim()Removes spaces" Hi ".trim() → "Hi"
split(String regex)Splits string into array"a,b,c".split(",") → ["a","b","c"]
replace(char old, char new)Replace characters"Java".replace('a','o') → "Jovo"
indexOf(String s)First occurrence"Hello".indexOf("l") → 2
lastIndexOf(String s)Last occurrence"Hello".lastIndexOf("l") → 3
toUpperCase()/toLowerCase()Case conversion"Hello".toUpperCase() → "HELLO"

4️⃣ String vs StringBuilder vs StringBuffer

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread SafeNoNoYes
PerformanceSlow for concatFastSlower than SB
UsageSmall string operationsLots of changes in stringMultithreaded environment
String s = "Hello";
s = s + " World";  // Creates new string

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies original object

5️⃣ Common String Interview Questions (Java + Selenium + RestAssured)

A. Java String Questions

  1. Difference between == and .equals() in String.

  2. What is immutability of String and why is it useful?

  3. Difference between String, StringBuilder, and StringBuffer.

  4. How does String pool work?

  5. Reverse a string in Java.

String str = "Java";
String rev = new StringBuilder(str).reverse().toString();
  1. Count occurrence of a character in a string.

  2. Check if a string is palindrome.

  3. Remove duplicates from a string.


B. Selenium String Questions

  1. How to verify text of a WebElement?
String actualText = driver.findElement(By.id("demo")).getText();
String expectedText = "Hello";
Assert.assertEquals(actualText, expectedText);
  1. How to split a table cell text into multiple values?
String cellText = "Name: John, Age: 25";
String[] data = cellText.split(",");
  1. How to trim spaces before asserting text?

C. RestAssured String Questions

  1. How to extract value from JSON response?
String response = given().get("/users/1").asString();
String name = JsonPath.from(response).getString("name");
  1. How to assert response contains a value?
Assert.assertTrue(response.contains("John"));
  1. How to validate JSON schema using strings?
given().get("/users/1").then().assertThat()
       .body(matchesJsonSchemaInClasspath("schema.json"));
  1. How to replace placeholders in dynamic endpoints?
String endpoint = "/users/{id}";
endpoint = endpoint.replace("{id}", "1");

6️⃣ Tips for Automation Interviews

  • Be clear on String immutability and comparison (== vs .equals()).

  • Know common String methods and their use in Selenium & RestAssured.

  • Be ready to manipulate API response strings (split, substring, regex).

  • Practice parsing JSON or XML strings.

Java String Interview Questions – Selenium & RestAssured Focus


1️⃣ Basics of String

Q1. What is a String in Java?
A: A String represents a sequence of characters. It is an object of the java.lang.String class.

String str = "Hello";

Q2. What is the difference between == and .equals() for Strings?

  • == → compares reference (memory location)

  • .equals() → compares actual content

String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1 == s2);       // false
System.out.println(s1.equals(s2));  // true

Q3. Why are Strings immutable in Java?

  • To save memory via String Pool.

  • Thread-safe (safe for multiple threads).

  • Security reasons (used in credentials, keys, etc.).

Q4. Difference between String, StringBuilder, and StringBuffer

FeatureStringStringBuilderStringBuffer
MutableNoYesYes
Thread SafeNoNoYes
PerformanceSlow for concatFastSlightly slower
UseConstant stringMultiple changesMulti-threaded changes

Q5. How to create String objects?

String s1 = "Hello"; // literal
String s2 = new String("Hello"); // constructor
char[] arr = {'J','a','v','a'};
String s3 = new String(arr); // from char array

2️⃣ String Methods

Q6. How to get length of a string?

String s = "Hello";
System.out.println(s.length()); // 5

Q7. How to get a character at a position?

System.out.println(s.charAt(1)); // 'e'

Q8. How to extract substring?

System.out.println(s.substring(1,4)); // "ell"

Q9. How to check if a string contains a substring?

System.out.println(s.contains("ell")); // true

Q10. How to convert string to upper or lower case?

System.out.println(s.toUpperCase()); // "HELLO"
System.out.println(s.toLowerCase()); // "hello"

Q11. How to trim spaces?

String str = "  Hello  ";
System.out.println(str.trim()); // "Hello"

Q12. How to replace characters or words?

String str = "Java";
System.out.println(str.replace('a','o')); // "Jovo"
System.out.println(str.replace("Java","Python")); // "Python"

Q13. How to split a string?

String str = "a,b,c";
String[] arr = str.split(",");
System.out.println(Arrays.toString(arr)); // [a, b, c]

3️⃣ String Manipulation

Q14. Reverse a string

String str = "Java";
String rev = new StringBuilder(str).reverse().toString();
System.out.println(rev); // "avaJ"

Q15. Count occurrence of a character

String str = "hello";
long count = str.chars().filter(c -> c=='l').count();
System.out.println(count); // 2

Q16. Check palindrome

String str = "madam";
String rev = new StringBuilder(str).reverse().toString();
System.out.println(str.equals(rev)); // true

Q17. Remove duplicates from a string

String str = "hello";
String result = Arrays.stream(str.split("")).distinct().collect(Collectors.joining());
System.out.println(result); // "helo"

4️⃣ String & Selenium

Q18. How to verify text of WebElement?

String actual = driver.findElement(By.id("demo")).getText();
String expected = "Hello";
Assert.assertEquals(actual, expected);

Q19. How to split table cell text?

String cellText = "Name: John, Age: 25";
String[] data = cellText.split(",");

Q20. How to trim before asserting text?

String text = driver.findElement(By.id("demo")).getText().trim();

Q21. How to check if element text contains a substring?

String text = driver.findElement(By.id("demo")).getText();
Assert.assertTrue(text.contains("John"));

Q22. Convert WebElement text to uppercase/lowercase

String text = driver.findElement(By.id("demo")).getText().toUpperCase();

5️⃣ String & RestAssured

Q23. Extract value from JSON response

String response = given().get("/users/1").asString();
String name = JsonPath.from(response).getString("name");

Q24. Assert response contains value

Assert.assertTrue(response.contains("John"));

Q25. Validate JSON schema

given().get("/users/1").then().assertThat()
       .body(matchesJsonSchemaInClasspath("schema.json"));

Q26. Replace placeholder in endpoint

String endpoint = "/users/{id}";
endpoint = endpoint.replace("{id}", "1");

Q27. Extract array from JSON response

List<String> names = JsonPath.from(response).getList("users.name");

6️⃣ Advanced Questions

Q28. Difference between intern() and normal string creation

  • intern() → Returns reference from String Pool.
String s1 = new String("Hello").intern();
String s2 = "Hello";
System.out.println(s1 == s2); // true

Q29. Convert String to char array

char[] arr = "Hello".toCharArray();

Q30. Convert String to integer/number

int num = Integer.parseInt("123");

Q31. Convert integer to string

String str = String.valueOf(123);

Q32. Compare strings ignoring case

"Hello".equalsIgnoreCase("hello"); // true

Q33. Check if string starts or ends with substring

"Hello".startsWith("He"); // true
"Hello".endsWith("lo");   // true

Q34. Remove white spaces from entire string

String str = " H e l l o ";
str = str.replaceAll("\\s","");

Q35. Check if string is empty or blank

"".isEmpty();   // true
"  ".isBlank(); // true in Java 11+

7️⃣ Regex with String (Useful for Selenium & API)

Q36. Check if string contains only digits

String str = "12345";
boolean isDigit = str.matches("\\d+"); // true

Q37. Validate email pattern

String email = "test@gmail.com";
boolean valid = email.matches("^[A-Za-z0-9+_.-]+@(.+)$");

Q38. Extract numbers from string

String str = "Price: 100 USD";
String num = str.replaceAll("\\D",""); // 100

Q39. Split string using regex

String str = "a1b2c3";
String[] parts = str.split("\\d"); // [a,b,c]

8️⃣ Performance & Memory Questions

Q40. Why string concatenation with + is slow?

  • Because it creates new String objects every time. Use StringBuilder for multiple changes.

Q41. What is String Pool?

  • Memory area in heap that stores literal strings. Reuses objects to save memory.

Q42. Difference between String literal and new String()

  • Literal → stored in pool

  • new String() → stored in heap

Q43. What happens when you concatenate strings in a loop?

String s = "";
for(int i=0;i<100;i++){
    s += i; // creates 100+ objects → memory inefficient
}

9️⃣ Miscellaneous Questions

Q44. Extract substring between two characters

String str = "Name: John Age:25";
String sub = str.substring(str.indexOf(":")+2, str.indexOf(" Age")); // "John"

Q45. Reverse words in a sentence

String sentence = "I love Java";
String reversed = Arrays.stream(sentence.split(" "))
                        .collect(Collectors.collectingAndThen(Collectors.toList(), l -> {
                            Collections.reverse(l);
                            return String.join(" ", l);
                        }));

Q46. Count words in a string

String str = "I love Java";
int words = str.trim().split("\\s+").length; // 3

Q47. Check if two strings are anagrams

char[] a = "listen".toCharArray();
char[] b = "silent".toCharArray();
Arrays.sort(a); Arrays.sort(b);
System.out.println(Arrays.equals(a,b)); // true

Q48. Remove special characters from string

String str = "He@l#l$o!";
str = str.replaceAll("[^a-zA-Z0-9]","");

Q49. Convert string to list of characters

List<Character> list = str.chars().mapToObj(c -> (char)c).collect(Collectors.toList());

Q50. Convert string to stream for processing

String str = "Hello";
str.chars().forEach(c -> System.out.println((char)c));

✅ Tips for Interviews

  1. Know string immutability and comparison (== vs .equals) well.

  2. Be ready to manipulate API response strings in RestAssured.

  3. Be confident in splitting, trimming, extracting substrings in Selenium validation.

  4. Practice regex with strings for data validation.

  5. Know performance differences between String vs StringBuilder vs StringBuffer.

More from this blog

SS-JAVA

23 posts