String Flashcards

1
Q

What is meant by Immutable in the context of Strings?

A

An immutable object cannot be modified in java. String is an immutable class in java. Once a string is created it cannot be changed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why a string is considered immutable?

A

There is a concept of string literal in java. If there are two String variables that reference to a String object “Test”, both these variables reference the same string literal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How many ways are there to create a string?

A

There are two ways to create a String, one by using String literal and the other by using the “new” operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why does java use string literals?

A

To make java more efficient in memory. If a string already exists in the string constant pool, it can be reused.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the main difference between a String and StringBuffer object.

A

String is an immutable object, its value cannot change after creation. StringBuffer is a mutable object. We can keep modifying the contents of a StringBuffer in java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you make a class immutable in java?

A

Mark it as final to prevent it from being extended. Add private modifier to all the fields to prevent direct access. Do not provide setter methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the use of toString() in java?

A

Object class has a toString() method. This can be used to return the string representation of an object. Java provides default implementation for the toString method, but it can be overridden.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Arrange String, stringbuffer and stringbuilder in order of efficiency?

A

StringBuilder is the most efficient class, then StringBuffer, then String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly