0% found this document useful (0 votes)
23 views7 pages

SPM Unit6

This document provides an overview of Strings in Java, detailing their characteristics as immutable objects and the use of the java.lang.String class for string manipulation. It covers various methods for creating strings, inbuilt string methods, and operations on strings without using built-in functions, as well as the concept of substrings. Additionally, it discusses the importance of string immutability, the Java String Pool, and the differences between String, StringBuilder, and StringBuffer classes.

Uploaded by

Vinit Pansuriya
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)
23 views7 pages

SPM Unit6

This document provides an overview of Strings in Java, detailing their characteristics as immutable objects and the use of the java.lang.String class for string manipulation. It covers various methods for creating strings, inbuilt string methods, and operations on strings without using built-in functions, as well as the concept of substrings. Additionally, it discusses the importance of string immutability, the Java String Pool, and the differences between String, StringBuilder, and StringBuffer classes.

Uploaded by

Vinit Pansuriya
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/ 7

UNIT 6 STRINGS

→ Generally, String is a sequence of characters. But in Java, String is an object that represents a
sequence of characters.
→ The java.lang.String class is used to create a string object.
→ Strings are immutable, which means that once a string is created, its value cannot be changed.
→ Java Strings are typically a data type but often treated as a data structure.
→ It stores the elements of character type sequentially, just as an array does. Each letter in the string
is a separate character value that makes up the Java string object.
→ Users can write an array of char values that will mean the same thing as a string.
→ Strings are used in a wide variety of applications, including web development, database
development, and game development.

6.1 String class


6.2 Inbuilt String methods
6.3 Operations on String without using inbuilt functions
6.4 Concept of Substring

6.1 STRING CLASS

→ A String is a final class in Java that extends java.lang.


→ It is an object which is represented as immutable sequences of characters.
→ Strings are created using the String constructor or by string literals.
→ All the string literals are treated as instances of the String class.
→ String objects are stored in a special memory area known as the "string constant pool".
→ Java Strings can perform various string manipulation operations.

Prepared by : Prof. Lavleena Stephens


DIFFERENT WAYS TO CREATE A STRING IN JAVA

• Using String literal


− This is the most common way of creating string. In this case a string literal is enclosed with
double quotes.
− Example : String str = "abc";
− When we create a String using double quotes, JVM looks in the String pool to find if any
other String is stored with same value. If found, it just returns the reference to that String
object else it creates a new String object with given value and stores it in the String pool.
• Using new keyword
− We can create String object using new operator, just like any normal java class. There are
several constructors available in String class to get String from char array, byte array,
StringBuffer and StringBuilder.
− Example 1 : String str = new String("abc");
− Example 2 : char[] a = {'a', 'b', 'c'};
String str2 = new String(a);

6.2 INBUILT STRING METHODS

→ Strings are immutable, which means that once a string is created, its value cannot be changed.
→ If you need to modify a string, you can create a new string containing the desired changes.
→ The String class provides a variety of methods for manipulating strings, including:

Method Description Return Type


charAt() Returns the character at the specified index (position) char
compareTo() Compares two strings lexicographically int
compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences int
concat() Appends a string to the end of another string String
contains() Checks whether a string contains a sequence of characters boolean

contentEquals() Checks whether a string contains the exact same sequence of boolean
characters of the specified CharSequence or StringBuffer

endsWith() Checks whether a string ends with the specified character(s) boolean

equals() Compares two strings. Returns true if the strings are equal, and false if boolean
not
equalsIgnoreCase() Compares two strings, ignoring case considerations boolean

format() Returns a formatted string using the specified locale, format string, and String
arguments

getChars() Copies characters from a string to an array of chars void

indexOf() Returns the position of the first found occurrence of specified int
characters in a string

Prepared by : Prof. Lavleena Stephens


isEmpty() Checks whether a string is empty or not boolean

lastIndexOf() Returns the position of the last found occurrence of specified characters int
in a string

length() Returns the length of a specified string int

matches() Searches a string for a match against a regular expression, and returns boolean
the matches

replace() Searches a string for a specified value, and returns a new string where String
the specified values are replaced

replaceFirst() Replaces the first occurrence of a substring that matches the given String
regular expression with the given replacement

replaceAll() Replaces each substring of this string that matches the given regular String
expression with the given replacement

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with specified characters boolean

substring() Returns a new string which is the substring of a specified string String

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String

valueOf() Returns the string representation of the specified value String

isBlank() vs isEmpty()

Both methods are used to check for blank or empty strings in java.
The difference between both methods is that:
• isEmpty() method returns true if, and only if, the string length is 0.
• isBlank() method only checks for non-whitespace characters. It does not check the string
length.
In other words, a String with only white space characters is blank but not empty.
Examples :
"ABC".isBlank() //false
" ".isBlank() //true

"ABC".isEmpty() //false
" ".isEmpty() //false

Prepared by : Prof. Lavleena Stephens


Example :
String myString = "Hello, world!";
System.out.println("Original string : " + myString);

// Get the length of the string


System.out.println("String length" + myString.length());

// Get the character at the specified index


System.out.println("Char at index 4" + myString.charAt(4));

// Find the index of the first occurrence of the specified character or substring
System.out.println(myString.indexOf('o'));
// will be equal to 4

// Extract a substring of the string


System.out.println(myString.substring(0, 5));
// will be equal to "Hello"

// Concatenate two strings together


System.out.println("Concatenation : "+myString.concat("!"));
// will be equal to "Hello, world!!"

// Replace all occurrences of the specified character or substring in the string with the specified
replacement character or substring
System.out.println(myString.replace(",", " "));
// will be equal to "Hello world!"

// Split the string into an array of strings, using the specified delimiter
String[] strArray = myString.split(",");
// strArray will be an array containing the strings "Hello" and " world!"

for(int i=0; i<strArray.length; i++)


System.out.println(strArray[i]);

6.3 OPERATIONS ON STRING WITHOUT USING INBUILT FUNCTIONS

Performing operations on strings without using built-in functions in Java involves manually implementing
the functionality for common string operations.
To perform operations on strings without using inbuilt functions in Java, you can use the following steps:
1. Convert the string to a character array.
2. Perform the desired operation on the character array.
3. Convert the character array back to a string.

Prepared by : Prof. Lavleena Stephens


Converting a String to a char array
String str = “Java”;
char[] chars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
chars[i] = str.charAt(i);
}
// array chars will contain elements [‘J’, ’a’, ’v’, ’a’]

Following are some programs to practice which you can implement without using in-built functions :

• Finding length of string


• Retrieving a character at a specified index
• Replace a character
• Reverse a string
• Check if a string is a palindrome
• Count the number of occurrences of a character in a string
• Split a String into an array of Strings

6.4 CONCEPT OF SUBSTRING

→ The substring() method in Java is used to extract a substring from a given string.
→ It returns a new string that is a substring of this string.
→ In Java, Substring is a part of a String or can be said subset of the String.
→ There are two variants of the substring() method.
→ It can be used to extract substrings from different positions within a string.
→ If the endIndex argument is not specified, then the substring will extend to the end of the string.
→ There are two variants of the substring() method:
• public String substring(int startIndex)
• public String substring(int startIndex, int endIndex)

String substring()
→ The substring begins with the character at the specified index and extends to the end of this
string.
→ Endindex of the substring starts from 1 and not from 0.
Syntax
public String substring(int begIndex);
Parameters
• begIndex: the start index, inclusive.
Return Value
• The specified substring.

Prepared by : Prof. Lavleena Stephens


String substring(begIndex, endIndex)
→ The substring begins at the specified start index and ends at the specified end index.
Syntax
public String substring(int begIndex, int endIndex);
Parameters
• beginIndex : the start index, inclusive.
• endIndex : the end index, exclusive.
Return Value
• The specified substring.
Here are some examples of how the substring() method can be used in real-world applications:

• To extract the domain name from a web address.


• To extract the username from an email address.
• To extract the date from a timestamp.
• To extract the filename from a path.
• To extract the first or last word from a sentence.

EXTRA POINTS
Why is String immutable in Java ?
The String is the most widely used data structure. Caching the String literals and reusing them saves a lot of
heap space because different String variables refer to the same object in the String pool. String intern pool
serves exactly this purpose.

Java String Pool is the special memory region where Strings are stored by the JVM. Since Strings are
immutable in Java, the JVM optimizes the amount of memory allocated for them by storing only one copy
of each literal String in the pool. This process is called interning:
Example:
String s1 = "Hello World";
String s2 = "Hello World";
assertThat(s1 == s2).isTrue();

Because of the presence of the String pool in the preceding example, two different variables are pointing to
same String object from the pool, thus saving crucial memory resource.
Prepared by : Prof. Lavleena Stephens
Example:
// Demonstrating String immutability
String s1 = "Java";
s1.concat(" programming");
System.out.println("s1 : " + s1); // will print only “Java”

TYPES OF STRING CLASSES


There are two types of character sequence classes in Java. The immutable class which is the String class,
and the mutable class which is StringBuilder and StringBuffer.
When it comes to efficiency, StringBuilder is more efficient than StringBuffer.

StringBuffer
StringBuffer is thread-safe and synchronized. That means no two threads can simultaneously access
methods of string buffer.
Example:
StringBuffer bufferstring=new StringBuffer("I am stringbuffer.");
bufferstring.append("I am thread safe.");
System.out.println(bufferstring);

StringBuilder
StringBuilder is non-synchronized and is not thread-safe. That means two threads can simultaneously
access methods of string buffer.
Example:
StringBuilder builderstring=new StringBuilder("I am stringbuilder.");
builderstring.append("I am more efficient than string buffer.");
System.out.println(builderstring);

Prepared by : Prof. Lavleena Stephens

You might also like