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

String

String in java

Uploaded by

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

String

String in java

Uploaded by

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

Q. What is String?

In Java, the String class represents a sequence of characters. It's one of the most commonly used
classes in Java, and it's part of the java.lang package, so you don't need to import it explicitly. Strings
are used to store and manipulate text data.

Key Characteristics of String in Java:


1. Immutability:
 A String in Java is immutable, which means once a String object is created, it cannot be
changed. Any modification to a String results in the creation of a new String object.

 For example, when you concatenate two strings, a new String object is created, and the
original strings remain unchanged.

Example:

String s1 = "Hello";

String s2 = s1 + " World"; // A new String "Hello World" is created

2.String Pool:
 Java optimizes memory usage by storing string literals in a special memory area known as the
String Pool.

 When you create a string literal, Java checks the String Pool first. If the string already exists in
the pool, the existing reference is returned; otherwise, the string is added to the pool.

Example:

String s1 = "Hello";

String s2 = "Hello"; // s1 and s2 refer to the same object in the String Pool

3. String Interning:
 You can explicitly add a string to the String Pool using the intern() method.

 If the string is already in the pool, intern() returns the reference from the pool; otherwise, it
adds the string to the pool and returns the reference.

Example:

String s1 = new String("Hello");

String s2 = s1.intern(); // s2 will refer to the String Pool instance of "Hello"

4. Two ways of Creating Strings:


a.Literal: When you assign a string literal, it is stored in the String Pool.

String s1 = "Hello"; // Stored in the String Pool

b.Using new Keyword: When you create a string using the new keyword, a new object is
created on the heap, and the literal may or may not be placed in the String Pool.
String s2 = new String("Hello"); // New object on the heap

5. Common String Operations:


 Concatenation: Combining two strings.
String s = "Hello" + " World"; // "Hello World"
 Length: Getting the number of characters in a string.
int length = s.length(); // Length of "Hello World" is 11
 Substring: Extracting a portion of a string.
String sub = s.substring(0, 5); // "Hello"
 CharAt: Accessing a character at a specific index.
char c = s.charAt(0); // 'H'
 Equals: Comparing two strings for content equality
boolean isEqual = s.equals("Hello World"); // true
 CompareTo: Lexicographically comparing two strings
int result = s.compareTo("Hello"); // Positive number
 Contains: Checking if a string contains a sequence of characters.
boolean contains = s.contains("World"); // true

6. String Manipulation Methods:


 toUpperCase / toLowerCase: Convert the string to uppercase or lowercase.

String upper = s.toUpperCase(); // "HELLO WORLD"

String lower = s.toLowerCase(); // "hello world"

 Replace: Replace characters or sequences within the string

String replaced = s.replace("World", "Java"); // "Hello Java"

 Trim: Remove leading and trailing whitespace.


String trimmed = s.trim(); // "Hello World"

7. String Comparisons:
 == vs equals():
1. == checks if two references point to the same object.
2. equals() checks if two strings have the same content.
Example:
String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1 == s2); // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)

8. Immutable Nature and Security:


 The immutability of strings ensures that once a string is created, it cannot be altered. This is
particularly useful for security, such as in handling passwords, where modifications to the
string object are not possible.

Q. What is StringBuilder?
 Mutability:

StringBuilder is mutable, meaning it can be modified after it is created. Unlike String,


operations on a StringBuilder object modify the original object itself.

 Performance:

StringBuilder is faster than String when performing multiple modifications like


concatenation, insertion, or deletion. This is because it does not create new objects with
every modification.

 Thread Safety:

StringBuilder is not thread-safe. It should not be used in a multi-threaded environment


where instances might be accessed concurrently without proper synchronization.

 Use Case:

Ideal for scenarios where you need to perform many modifications to a string, such as
building a string in a loop.

 Example:

StringBuilder sb = new StringBuilder("Hello");

sb.append(" World"); // Modifies the original StringBuilder object

System.out.println(sb.toString()); // Output: "Hello World"

Q. What is StringBuffer?
 Mutability:

Like StringBuilder, StringBuffer is mutable and can be modified after creation.

 Thread Safety:

StringBuffer is thread-safe because its methods are synchronized. This means it can be safely
used in a multi-threaded environment where the same instance might be accessed by
multiple threads.

 Performance:

Due to the overhead of synchronization, StringBuffer is generally slower than StringBuilder.


However, it is still faster than using immutable String objects for multiple modifications.
 Use Case:

StringBuffer is preferred when you need a mutable sequence of characters in a multi-


threaded environment.

o Example:

StringBuffer sb = new StringBuffer("Hello");

sb.append(" World"); // Modifies the original StringBuffer object

System.out.println(sb.toString()); // Output: "Hello World"

Feature String StringBuilder StringBuffer

Mutability Immutable Mutable Mutable

Thread Thread-safe
Not thread-safe Thread-safe
Safety (inherently)

Slower than
Slower for Faster for StringBuilder due to
Performance multiple multiple synchronization, but
changes changes faster than String for
multiple changes

Frequent string
Frequent string
Fixed strings, modifications in
modifications in a
Use Case few a single-
multi-threaded
modifications threaded
context
context

You might also like