Top Java String Interview Questions

Published: 22 August 2023
on channel: CloudTech
2,884
52

In this video we covered Java String Interview Questions which are often asked in the interview.

For Java Training Register at:
https://bit.ly/45HAwgf

Following are the questions:
Q.1) How can you create a String in Java?

Using Literal:
String str1 = “Hello";

Using Constructor:
String str2 = new String(“Hello");

How many objects will be created in case of Constructor?
2 String objects
One in heap and one in String Pool

Q.2) How do you compare two strings in Java?
Use the `equals()` method to compare the content of two strings for equality:

String str1 = "Hello";
String str2 = "Hello";
boolean areEqual = str1 == str2; // true

String str3 = new String(“Hello”);
String str4 = new String(“Hello”);

boolean isEqual = str3.equals(str4); // true

Q.3) How can you concatenate strings efficiently?
Use the `StringBuilder` class for efficient string concatenation, especially when dealing with multiple concatenations:

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

Q.4) How can you convert a string to uppercase/lowercase?
Use the `toUpperCase()` and `toLowerCase()` methods:

String original = "Hello World";
String upper = original.toUpperCase();
String lower = original.toLowerCase();

Q.5) Can you reverse a string in Java?
Yes, you can reverse a string using a loop or `StringBuilder`:

String original = "Hello";
String reversed = new StringBuilder(original).reverse().toString();

Q.6) What is the difference between `String`, `StringBuilder`, and `StringBuffer`?
`String`: Immutable, meaning the content cannot be changed after creation.
`StringBuilder`: Mutable and not thread-safe, suitable for single-threaded operations.
`StringBuffer`: Mutable and thread-safe, appropriate for multi-threaded operations.

Q.7)Explain the `substring()` method.
The `substring(int beginIndex)` method returns a new string that is a substring of the original string starting from the `beginIndex`.

Q.8) How do you check if a string contains a specific substring?
Use the `contains()` method:

String text = "Hello World";
boolean containsHello = text.contains("Hello");


On this page of the site you can watch the video online Top Java String Interview Questions with a duration of hours minute second in good quality, which was uploaded by the user CloudTech 22 August 2023, share the link with friends and acquaintances, this video has already been watched 2,884 times on youtube and it was liked by 52 viewers. Enjoy your viewing!