Top Java String Interview Questions

Veröffentlicht am: 22 August 2023
auf dem Kanal: 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");


Auf dieser Seite können Sie das Online-Video Top Java String Interview Questions mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer CloudTech 22 August 2023 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 2,884 Mal angesehen und es wurde von 52 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!