0% found this document useful (0 votes)
6 views

String Interview Questions

Uploaded by

vikashmaurya7235
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

String Interview Questions

Uploaded by

vikashmaurya7235
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1. What is a String in Java?

- Answer:

A `String` in Java is a sequence of characters, represented as objects. The `java.lang.String` class is immutable, meaning once
created, the content cannot be changed.

2. Why is String immutable in Java?

- Answer:

- Security: Prevents unauthorized access and modification.

- Thread-safety: Immutable objects are inherently thread-safe.

- HashMap compatibility: Since `String` is widely used as a key, immutability ensures hash codes remain constant.

3. What are the key differences between `String`, `StringBuilder`, and `StringBuffer`?

- Answer:

4. How can you compare Strings in Java?

- Answer:

- `==`: Compares references, not values.

- `.equals()`: Compares actual values of two strings.

- `.compareTo()`: Compares lexicographically; returns `0` if equal, negative if the first string is less, positive if greater.

5. What is the difference between `String` literal and `new String()`?

- Answer:

- String Literal: Stored in the String Pool. E.g., `String s1 = "Hello";`

- new String(): Creates a new object in the heap. E.g., `String s2 = new String("Hello");`

6. What are common String methods and their uses?

- Answer:
7. How does the `intern()` method work?

- Answer:

The `intern()` method moves the String object to the String Pool. If the pool already contains a string with the same content, it
returns the reference to the existing string.

8. What is the difference between `equals()` and `==`?

- Answer:

- `==`: Checks if two references point to the same object.

- `.equals()`: Checks if the content of the strings is the same.

9. How do you reverse a String in Java?

- Answer:

- Using `StringBuilder` or `StringBuffer`:

String str = "hello";

String reversed = new StringBuilder(str).reverse().toString();

String str = "hello";

String reversed = "";

for (int i = str.length() - 1; i >= 0; i--) {

reversed += str.charAt(i);
}

10. How can you check if a String is a palindrome?

- Answer:

Compare the string with its reversed version:

String str = "madam";

String reversed = new StringBuilder(str).reverse().toString();

boolean isPalindrome = str.equals(reversed);

11. How do you convert a String to a character array?

- Answer:

Using `toCharArray()`:

String str = "hello";

char[] charArray = str.toCharArray();

12. How can you join multiple strings in Java?

- Answer:

Use `String.join()`:

String result = String.join("-", "Java", "is", "fun");

// Output: Java-is-fun

13. What is the role of the `format()` method in Strings?

- Answer:

The `format()` method is used to create formatted strings:

String formatted = String.format("Hello, %s! You have %d new messages.", "Alice", 5);

14. How do you find duplicate characters in a String?

- Answer:

Use a `HashMap` to count occurrences:

String str = "programming";

Map<Character, Integer> map = new HashMap<>();

for (char c : str.toCharArray()) {

map.put(c, map.getOrDefault(c, 0) + 1);

map.forEach((k, v) -> {

if (v > 1) System.out.println(k + ": " + v);

});
15. What is the difference between `StringBuffer` and `StringBuilder`?

- Answer:

- `StringBuffer` is thread-safe but slower.

- `StringBuilder` is faster but not thread-safe.

16. Can a constructor be inherited in Java? Why or why not?

Answer:

No, constructors cannot be inherited in Java. Constructors are not members of a class; they are special methods used to initialize
objects. However, a subclass can call a parent class constructor using the `super()` keyword.

17. What is the difference between `super()` and `this()` in constructors?

- Answer:

- `super()

- Calls the constructor of the parent class.

- Must be the first statement in a constructor.

class Parent {

Parent() { System.out.println("Parent constructor"); }

class Child extends Parent {

Child() { super(); System.out.println("Child constructor"); }

- `this()

- Calls another constructor in the same class.

- Also must be the first statement in a constructor.

class Example {

Example() { this("Default"); }

Example(String msg) { System.out.println(msg); }

Note: You cannot use both `this()` and `super()` in the same constructor.

18. Can a constructor be private? What is its use?

- Answer:

Yes, a constructor can be private. It is typically used in:


- Singleton Design Pattern: To restrict object creation and ensure only one instance exists.

- Factory Methods: To control object creation through static methods.

```java

class Singleton {

private static Singleton instance;

private Singleton() { } // Private constructor

public static Singleton getInstance() {

if (instance == null) instance = new Singleton();

return instance;

19. What happens if a subclass does not explicitly call a superclass constructor?

- Answer:

If a subclass constructor does not explicitly call a superclass constructor using `super()`, the default (no-argument) constructor of
the superclass is automatically called.

If the superclass does not have a default constructor, the compiler will throw an error.

class Parent {

Parent(int x) { System.out.println("Parent constructor"); }

class Child extends Parent {

Child() { super(10); } // Explicit call to the parameterized parent constructor

20. How does the order of constructor execution work in inheritance?

- Answer:

In inheritance, constructors are executed in the order of the class hierarchy:

- The parent class constructor is called first.

- Then the child class constructor is executed.

This ensures that the parent class is initialized before the child class.

class Parent {

Parent() { System.out.println("Parent Constructor"); }

class Child extends Parent {

Child() { System.out.println("Child Constructor"); }

public class Test {


public static void main(String[] args) {

Child obj = new Child();

1. What is a constructor in Java?

- Answer:

A constructor is a special method used to initialize objects. It has the same name as the class and no return type. It is called
automatically when an object is created.

2. What are the types of constructors in Java?

- Answer:

- Default Constructor: Provided by Java if no constructor is defined; initializes objects with default values.

- Parameterized Constructor: Takes arguments to initialize an object with specific values.

3. Can a constructor be private? Why would you make it private?

- Answer:

Yes, a constructor can be private. It is often used in:

- Singleton Pattern: To restrict instantiation to a single object.

- Factory Methods: To control object creation.

4. Can a constructor call another constructor in the same class? How?

- Answer:

Yes, using `this()`:

class Example {

Example() {

this(10); // Calls parameterized constructor

Example(int x) {

System.out.println(x);

5. What is the difference between a constructor and a method?

- Answer:
1. What is inheritance in Java? Why is it used?

- Answer:

Inheritance is a mechanism where one class (child) acquires the properties and behaviors of another class (parent). It is used to
promote code reuse and establish a relationship between classes.

2. What are the types of inheritance in Java?

- Answer:

- Single Inheritance: One class inherits from another.

- Multilevel Inheritance: A class inherits from a class that is already inherited.

- Hierarchical Inheritance: Multiple classes inherit from a single parent class.

Note: Java does not support multiple inheritance (via classes) to avoid ambiguity (diamond problem).

3. What is the difference between `super` and `this` keywords in inheritance?

- Answer:

- `super`: Refers to the parent class (e.g., `super.methodName()`).

- `this`: Refers to the current class (e.g., `this.variableName`).

4. Can a subclass override a method from the parent class? What are the rules?

- Answer:

Yes, a subclass can override methods. Rules include:

- The method must have the same name, return type, and parameters.

- The method cannot have a stricter access modifier.

- `final` or `static` methods cannot be overridden.

5. What is the difference between `IS-A` and `HAS-A` relationships in Java?

- Answer:

- `IS-A` Relationship: Achieved through inheritance; represents "is a type of" (e.g., `Dog` IS-A `Animal`).

- `HAS-A` Relationship: Achieved through composition; represents "has a" (e.g., `Car` HAS-A `Engine`).

You might also like