DSA Module 4 Java Strings Methods 1week
DSA Module 4 Java Strings Methods 1week
Unit 4
Java String Methods
Introduction
Strings in Java are widely used data type (and in most programming
languages), they allow us to store anything and everything that has to do with words,
sentences, phone numbers, or even just regular numbers. But, as useful as they are,
you’ll need to know a few important things about Strings before you go wild using
them in your code.
In this unit, you will be exposed to the different string methods used in Java
to manipulate string types of data.
Learning Objectives
When you hear the following terms, what comes in your mind. Write your ideas on
the space provided in each column.
1
Unit 4: Java String Methods
Array String
2
Unit 4: Java String Methods
Presentation of Contents
The following discussion was based from Johari (2020), he defined string as a
sequence of characters. But in Java, a string is an object that represents a sequence of
characters. The java.lang.String class is used to create string object.
Java String Pool: Java String pool refers to collection of Strings which are
stored in heap memory. In this, whenever a new object is created, String pool first
checks whether the object is already present in the pool or not. If it is present, then
same reference is returned to the variable else new object will be created in the
String pool and the respective reference will be returned. Refer to the diagrammatic
representation for better understanding:
In the above image, two Strings are created using literal i.e “Apple” and
“Mango”. Now, when third String is created with the value “Apple”, instead of
creating a new object, the already present object reference is returned. That’s the
reason Java String pool came into the picture.
Before we go ahead, one key point I would like to add that unlike other data
types in Java, Strings are immutable. By immutable, we mean that Strings are
3
Unit 4: Java String Methods
constant, their values cannot be changed after they are created. Because String
objects are immutable, they can be shared. For example:
String str =”abc”; is equivalent to:
4
Unit 4: Java String Methods
Exercise 3.1
Name: _________________________________________ BSIT 2 ___ Score: ___
2. Use the variable “name” to declare the letters of your family name.
3. Use the variable “contact” to declare the digits of your contact number.
5
Unit 4: Java String Methods
String Methods
The following string methods were based from Java Society (2019). The
methods and actions were provided to easily apply and trace the program.
1. int length(): Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i): Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’
3. String substring (int i): Return the substring from the ith index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
4. String substring (int i, int j): Returns the substring from i to j-1 index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
5. String concat( String str): Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
6. int indexOf (String s): Returns the index within the string of the first occurrence of
the specified string.
String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
7. int indexOf (String s, int i): Returns the index within the string of the first
occurrence of the specified string, starting at the specified index.
String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13
8. int lastIndexOf( String s): Returns the index within the string of the last
occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
9. boolean equals( Object otherObj): Compares this string to the specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
10. boolean equalsIgnoreCase (String anotherString): Compares string to another
string, ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
6
Unit 4: Java String Methods
Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase
or lowercase).
13. String toLowerCase(): Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
14. String toUpperCase(): Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
15. String trim(): Returns the copy of the String, by removing whitespaces at both
ends. It does not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
16. String replace (char oldChar, char newChar): Returns new string by replacing
all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”
7
Unit 4: Java String Methods
import java.io.*;
import java.util.*;
class Test
{
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");
8
Unit 4: Java String Methods
// Converting cases
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +
word1.toLowerCase());
// Converting cases
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +
word1.toUpperCase());
// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}
Output:
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
9
Unit 4: Java String Methods
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equality false
If s1 = s2 false
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks
10
Unit 4: Java String Methods
Exercise 3.2
Name: _________________________________________ BSIT 2 ___ Score: _____
Output Tracing. Trace and give the exact output of the following program fragments.
16. System.out.print(S2.charAt(15));
_______________________
17. System.out.print(S3.indexOf(“mo”));
_______________________
18. System.out.print(S1.substring(16));
_______________________
19. System.out.print(S2.replace(‘o’, ‘e’));
________________________________________________________
________________________________________________________
20. System.out.print(S3.lastIndexOf(“a”));
_____________________
21. System.out.print(S1.length());
_____________________
22. String S4 = S2.substring(23, 29);
System.out.print(S4);
_____________________
23. String S5 = S3.substring(27, 36);
System.out.print(S5.concat(S4));
______________________
24. System.out.print(S4.toUpperCase());
______________________
25. System.out.print(S5.replace(‘a’, ‘u’));
______________________
The table below compares a string from a character of arrays according to Java
Society (2019).
11
Unit 4: Java String Methods
‘+’ can be used to appended strings ‘+’ cannot be used to append two
together to form a new string. Character Arrays.
The charAt() method can be used to access The characters in a Character Array
characters at a particular index in a String. can be accessed normally like in
any other language by using [].
Strings can be stored in any manner in the Elements in Character Array are
memory. stored contiguously in increasing
memory locations.
All Strings are stored in the String All Character Arrays are stored in
Constant Pool. the Heap.
12
Unit 4: Java String Methods
Exercise 3.3
Name: ___________________________________________ BSIT 2 ___ Score: _____
Read the following statements carefully. Write “S” if the statement describes a string
otherwise write “CA” if the statement describes a character array. Write your answer on the
space provided before each item.
_____ 10. The charAt() method can be used to access characters at a particular index of the
elements.
13
Unit 4: Java String Methods
Application 3
1. Create a program prototype that will ask the user to enter a sentence. Answer
the following by writing the code/statement that gives solution to the following
questions:
14
Unit 4: Java String Methods
I. Identification. Read and analyze the following statements about Java strings, then
identify what is being described and write your answer on the space provided
after each item.
1. A method that returns the index within the string of the last occurrence of the
specified string. _____________________
2. This method returns new string by replacing all occurrences
of oldChar with newChar. _____________________
3. Concatenation on specified string to the end of a string is possible through this
method. _________________________
4. It returns the number of characters in the String. This method is known as
_______________________
5. This method converts all the characters in the String to lower case.
___________________________
6. Through this method, it returns the index within the string of the first occurrence
of the specified string, starting at the specified index. _____________________
7. This method is used to compares string to another string, ignoring case
considerations. ________________________
8. A method used to return the index within the string of the first occurrence of the
specified string. _______________________
9. This method is used to compare two string lexicographically, ignoring case
considerations. __________________________
10. It returns the substring from the ith index character to end. This method is
called the ________________________
11. It is a sequence of characters which are immutable which means a constant and
cannot be changed once created. ______________________
12. It is a collection of objects having different data types, also known as record.
_____________________
For items 13 to 15, identify the parts of a string declaration.
13 14 15
15
Unit 4: Java String Methods
II. Output Tracing. Trace and give the exact output of the following program
fragments.
16. System.out.print(S2.charAt(15));
_______________________
17. System.out.print(S3.indexOf(“mo”));
_______________________
18. System.out.print(S1.substring(16));
_______________________
19. System.out.print(S2.replace(‘o’, ‘e’));
________________________________________________________
________________________________________________________
20. System.out.print(S3.lastIndexOf(“a”));
_____________________
21. System.out.print(S1.length());
_____________________
22. String S4 = S2.substring(8, 9);
System.out.print(S4);
_____________________
23. String S5 = S3.substring(12, 15);
System.out.print(S5.concat(S4));
______________________
24. System.out.print(S4.toUpperCase());
______________________
25. System.out.print(S5.replace(‘o’, ‘a’));
______________________
16
Unit 4: Java String Methods
Reflection 3
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
17
Unit 4: Java String Methods
Summary Unit
18
Unit 4: Java String Methods
References
19