String Handling in Java

Edu Tech Learner
0

 


String handling in Java is the process of manipulating and performing operations on strings, which are objects that represent sequences of characters. Java provides a lot of built-in methods and classes to work with strings, such as:


- The `java.lang.String` class, which implements the `CharSequence` interface and is immutable, meaning it cannot be changed once created. This class provides methods such as `concat()`, `equals()`, `length()`, `replace()`, `substring()`, etc

 

- The `java.lang.StringBuffer` class, which is a peer class of `String` that represents growable and writable character sequences. This class is mutable, meaning it can be modified, and thread-safe, meaning it can be used in multi-threaded environments. This class provides methods such as `append()`, `delete()`, `insert()`, `reverse()`, etc. 

 

- The `java.lang.StringBuilder` class, which is similar to `StringBuffer` but not thread-safe, meaning it is faster but not suitable for concurrent access. This class also provides methods such as `append()`, `delete()`, `insert()`, `reverse()`, etc. 

 

- The `java.util.regex` package, which provides classes and methods for performing regular expression operations on strings, such as matching, replacing, splitting, etc. For example, the `Pattern` class represents a compiled regular expression, and the `Matcher` class represents an engine that performs match operations on a character sequence by interpreting a `Pattern`.


To create a string object in Java, there are two ways: by using string literals or by using the `new` keyword. String literals are enclosed in double quotes and are stored in a special memory area known as the string constant pool. If a string literal already exists in the pool, a reference to the pooled instance is returned. If not, a new string object is created and placed in the pool. For example:

 

Code:-

```java

String s1 = "Hello"; // creates one string object and one reference variable

String s2 = "Hello"; // creates no new object but reuses the existing one

```


Using the `new` keyword creates a new string object in the normal (non-pool) heap memory and also places the string literal in the string constant pool. The variable will refer to the object in the heap (non-pool). For example:

 

Code:-

```java

String s3 = new String("Hello"); // creates two objects and one reference variable

```


To compare two strings for equality, the `equals()` method should be used instead of the `==` operator, as the latter compares the references rather than the contents of the strings. For example:

 

Code:-

```java

String s4 = "Hello";

String s5 = new String("Hello");

System.out.println(s4 == s5); // false

System.out.println(s4.equals(s5)); // true

```



Post a Comment

0Comments
Post a Comment (0)