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

The String Constructors, Various String Operations

Uploaded by

gayathris3884
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

The String Constructors, Various String Operations

Uploaded by

gayathris3884
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Module - 5

String: The String Constructors, Various String Operations

Dr.M.Gunasekar, AP/SCOPE Programming in Java


Strings
 String is a group of characters. They are objects of type String.
 Once a String object is created it cannot be changed.
 Strings are Immutable.
 To get changeable strings use the class called StringBuffer.
 String and StringBuffer classes are declared as final, so there cannot be subclasses of these classes.

String Creation methods:


 Using String Literal: When we create a string using a literal, Java checks the string pool (a special
memory area for storing strings) to see if an identical string already exists.
Example: String a = "Hello";
o If "Hello" exists in the pool, a will reference the existing object. If not, a new string is added to
the pool.
o This is memory-efficient because it reuses string instances.

 Using new Keyword:


Example: String b = new String("Hello");
o When we create a string using new, Java always creates a new object in the heap, regardless of
whether "Hello" exists in the string pool.
o This approach is less memory-efficient because it doesn't take advantage of the string pool.

 Using new and Assigning a Literal:


Example: String c = new String();
c = "Hello";
o String c = new String(); creates an empty String object in the heap.
o When we assign c = "Hello";, c now points to the "Hello" object in the string pool, and the empty
string initially created is eligible for garbage collection.
o This process is inefficient, as the initial new String() step is unnecessary.

 The intern() method ensures that the string is added to the string pool and returns the reference from the
pool, allowing more efficient memory use by avoiding duplicate string objects.
Example:
// Create a string using 'new', which creates a new object in the heap
String str1 = new String("Hello");

// Create a string literal; this goes into the string pool


String str2 = "Hello";

// Interning str1, which means str1 will now refer to the string from the pool
str1 = str1.intern();

Dr.M.Gunasekar, AP/SCOPE Programming in Java


String Constructors:

Constructor Description Example Code Snippet

Creates an empty string. String emptyString = new String();


String()
// Output: ""

Creates a string from the char[] chars = {'H', 'e', 'l', 'l', 'o'};
String(char[] value) String str = new String(chars);
specified character array.
// Output: "Hello"

Creates a string from a


String(char[] value, int offset, int String str = new String(chars, 1, 3);
portion of the specified
length) // Output: "ell"
character array.

Creates a string from the String original = "Hello"; String str =


String(String original) new String(original);
specified string.
// Output: "Hello"

Creates a string from the byte[] bytes = {72, 101, 108, 108,
String(byte[] bytes) 111}; String str = new String(bytes); //
specified byte array.
Output: "Hello"

Creates a string from a


String(byte[] bytes, int offset, int String str = new String(bytes, 0, 5);
portion of the specified
length) // Output: "Hello"
byte array.

StringBuffer buffer = new


Creates a string from the StringBuffer("Hello"); String str =
String(StringBuffer buffer)
specified StringBuffer. new String(buffer);
// Output: "Hello"
StringBuilder builder = new
Creates a string from the StringBuilder("Hello"); String str =
String(StringBuilder builder)
specified StringBuilder. new String(builder);
// Output: "Hello"

Dr.M.Gunasekar, AP/SCOPE Programming in Java


Various String Operations:

Method Method Declaration Description Example Code Snippet

String str = "Hello"; int len =


Returns the length
length() public int length() str.length();
of the string.
// Output: 5
Returns the
char ch = str.charAt(1);
charAt(int index) public char charAt(int index) character at the
// Output: 'e'
specified index.
Returns a
substring(int public String substring(int substring starting String sub = str.substring(2);
beginIndex) beginIndex) from the specified // Output: "llo"
index.
Returns a
substring(int substring from
public String substring(int String sub = str.substring(1,
beginIndex, int beginIndex to
beginIndex, int endIndex) 4); // Output: "ell"
endIndex) endIndex
(exclusive).
Compares the boolean isEqual =
public boolean equals(Object
equals(Object another) string to the str.equals("Hello");
another)
specified object. // Output: true
Compares the
public boolean boolean isEqual =
equalsIgnoreCase(String string to another
equalsIgnoreCase(String str.equalsIgnoreCase("hello");
another) string, ignoring
another) // Output: true
case.
Compares two int result =
compareTo(String public int compareTo(String
strings str.compareTo("World");
anotherString) anotherString)
lexicographically. // Output: Negative value
Converts all
String upper =
characters of the
toUpperCase() public String toUpperCase() str.toUpperCase();
string to
// Output: "HELLO"
uppercase.
Converts all
String lower =
characters of the
toLowerCase() public String toLowerCase() str.toLowerCase();
string to
// Output: "hello"
lowercase.
Removes leading
String trimmed = " Hello
and trailing
trim() public String trim() ".trim();
whitespace from
// Output: "Hello"
the string.

Dr.M.Gunasekar, AP/SCOPE Programming in Java


Replaces
String replaced =
replace(char oldChar, public String replace(char occurrences of
str.replace('l', 'p');
char newChar) oldChar, char newChar) oldChar with
// Output: "Heppo"
newChar.
Checks if the
public boolean boolean hasSeq =
contains(String string contains the
contains(CharSequence str.contains("ell");
sequence) specified
sequence) // Output: true
sequence.
Checks if the
boolean starts =
public boolean string starts with
startsWith(String prefix) str.startsWith("He");
startsWith(String prefix) the specified
// Output: true
prefix.
Checks if the
boolean ends =
public boolean string ends with
endsWith(String suffix) str.endsWith("lo");
endsWith(String suffix) the specified
// Output: true
suffix.
Returns the index
int index = str.indexOf('l');
indexOf(char ch) public int indexOf(int ch) of the first
// Output: 2
occurrence of ch.
Returns the index int lastIndex =
lastIndexOf(char ch) public int lastIndexOf(int ch) of the last str.lastIndexOf('l');
occurrence of ch. // Output: 3
Checks if the boolean empty = "".isEmpty();
isEmpty() public boolean isEmpty()
string is empty. // Output: true
String[] parts =
Splits the string
public String[] split(String "one,two,three".split(",");
split(String regex) around matches of
regex) // Output: ["one", "two",
the given regex.
"three"]
join(CharSequence
public static String Joins elements String joined = String.join("-",
delimiter,
join(CharSequence delimiter, with the specified "a", "b", "c");
CharSequence...
CharSequence... elements) delimiter. // Output: "a-b-c"
elements)
Converts the
String numStr =
public static String specified
valueOf(int i) String.valueOf(100);
valueOf(int i) argument to a
// Output: "100"
string.
Returns a String interned = str.intern();
intern() public String intern()
canonical // Interns the string "Hello"

Dr.M.Gunasekar, AP/SCOPE Programming in Java


representation for
the string object.
Converts the char[] chars =
toCharArray() public char[] toCharArray() string into a new str.toCharArray();
character array. // Output: ['H', 'e', 'l', 'l', 'o']
Tests if the string boolean matches =
public boolean matches(String
matches(String regex) matches the given "12345".matches("\\d+");
regex)
regex. // Output: true
Replaces each String replacedAll =
replaceAll(String regex, public String replaceAll(String
substring that "aabbcc".replaceAll("b", "x");
String replacement) regex, String replacement)
matches the regex. // Output: "aaxxcc"
Concatenates the
String combined =
public String concat(String specified string to
concat(String str) "Hello".concat(" World");
str) the end of this
// Output: "Hello World"
string.

Dr.M.Gunasekar, AP/SCOPE Programming in Java


Regular Expression:
 A regular expression (regex) in Java is a sequence of characters that defines a search pattern, typically
used for pattern matching within strings.
 Regular expressions allow for complex search patterns, such as finding specific substrings, validating
formats, or extracting portions of a string.
 Java provides the java.util.regex package to work with regular expressions, which includes two key
classes:
o Pattern: Represents a compiled regular expression.
o Matcher: Used to match the compiled pattern against a string.

 . (Dot): Matches any single character except a newline.


 * (Asterisk): Matches zero or more occurrences of the preceding character or group.
 + (Plus): Matches one or more occurrences of the preceding character or group.
 ? (Question Mark): Matches zero or one occurrence of the preceding character or group.
 ^ (Caret): Matches the beginning of the string.
 $ (Dollar Sign): Matches the end of the string.
 [] (Square Brackets): Defines a character class, matching any character within the brackets.
 | (Pipe): Represents the OR operator, matching either the pattern before or after it.
 () (Parentheses): Defines a capturing group, which can be used to extract parts of the matched string.
 \d: Matches any digit (0-9).
 \w: Matches any word character (letters, digits, underscores).
 \s: Matches any whitespace character (spaces, tabs, newlines).

Example:1
import java.util.regex.*;

public class LiteralMatch {


public static void main(String[] args) {
String text = "hello world";
String regex = ".*";

Pattern pattern = Pattern.compile(regex);


Matcher matcher = pattern.matcher(text);

if (matcher.find()) {
System.out.println("Found literal 'hello' in the text."+m.group());
} else {
System.out.println("Literal 'hello' not found.");
}
}
}

Example: 2
import java.util.regex.*;
public class RegexDigits {
public static void main(String[] args) {
String text = "Arun21BCE0001 bala24MIC0025";

Dr.M.Gunasekar, AP/SCOPE Programming in Java


String pattern = "(\\d{2})([A-Z]{3})(\\d{4})"; // Matches regno.

Pattern p= Pattern.compile(pattern);
Matcher matcher = p.matcher(text);

while(matcher.find()) {
System.out.println("complete Register no: "+matcher.group(0));
System.out.println("Batch: "+matcher.group(1));
System.out.println("Programmee: "+matcher.group(2));
System.out.println("Register no: "+matcher.group(3));
}
}
}

Dr.M.Gunasekar, AP/SCOPE Programming in Java

You might also like