Java Strings

Summary - Java Strings

Declaring and Initializing Strings

Strings are versatile and efficient in Java, used for storing and manipulating text.

String Initialization

Using literals: String firstName = "John";
Using new keyword: String firstName = new String("John");

String Concatenation

Combine strings using the + operator: String fullName = firstName + " " + lastName;

Memory Management

Literals: Utilizes string pooling for memory efficiency.
new Keyword: Creates a new string object each time, which can be less memory efficient.

String Immutability

Strings are immutable; once created, they cannot be changed.

Example

When modifying a string, a new string object is created, leaving the original unchanged.

Best Practices in Functional Programming

Key Principles

Immutability: Data structures cannot be altered after creation.
Pure Functions: Always produce the same output for the same input and have no side effects.

String Pooling and Interning

String Pooling

Reuses identical strings to save memory. Example: String str = "Hello";

String Interning

Adds strings created with new to the pool using .intern(). Example: String str2 = new String("Hello").intern();

Comparing Strings

Using ==

Compares memory locations. Example: String str2 = new String("Hello"); str == str2 is false.

Using .equals()

Compares values. Example: str.equals(str2) is true.

Handling Null Pointer Exceptions

Check for null before accessing string methods. Example: if (str != null) { /* use str */ }

String Methods and Operations

Basic Operations

Length: s.length()
CharAt: s.charAt(1)
Uppercase: s.toUpperCase()
Substring: s.substring(0, 5)
Split: s.split(", ")

StringBuilder vs StringBuffer

StringBuffer

Thread-safe and mutable.
Suitable for multi-threaded environments.

StringBuilder

Not thread-safe but faster.
Suitable for single-threaded contexts.

Intro to Regular Expressions (Regex)

Regex allows flexible text searching and manipulation.

Simplifying Validation

Use regex patterns for efficient validation. Example: Pattern pattern = Pattern.compile("\\d{10}");

Writing Basic Regex

Example Patterns

Direct matching: abc
Character classes: [abc]
Negation: [^abc]
Ranges: [a-z]
Repetition: a{3}
Quantifiers: *, +, ?

Using Regex in Java

Extracting Patterns

Use Pattern and Matcher classes to find and extract patterns, such as email addresses or phone numbers.

Anchors

Start of line: ^
End of line: $
Understanding these Java concepts helps in building efficient, modular, and maintainable software systems. For more detailed information, refer to the Notion link:
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.