Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

DSA Module 4 Java Strings Methods 1week

The document discusses the Java String methods unit. It provides an introduction to strings in Java and outlines the unit learning objectives which are to declare and explain string data types, execute and trace string methods, and distinguish when to use character arrays or strings. It then discusses specific string methods like length(), charAt(), substring(), concat(), indexOf(), equals(), compareTo(), toLowerCase(), and replace(). It provides examples of each method and a sample program to illustrate using multiple string methods.

Uploaded by

Marnel Mogado
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

DSA Module 4 Java Strings Methods 1week

The document discusses the Java String methods unit. It provides an introduction to strings in Java and outlines the unit learning objectives which are to declare and explain string data types, execute and trace string methods, and distinguish when to use character arrays or strings. It then discusses specific string methods like length(), charAt(), substring(), concat(), indexOf(), equals(), compareTo(), toLowerCase(), and replace(). It provides examples of each method and a sample program to illustrate using multiple string methods.

Uploaded by

Marnel Mogado
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Unit 4: Java String Methods

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.

Unit Learning Outcomes

At the end of the unit, you will be able to:


a. declare and explain string data types appropriately;
b. execute and trace the different string methods; and
c. distinguish instances when to use array of characters or string.

Topic 1: String Methods


Time Allotment: 2 Hours

Learning Objectives

At the end of the session, you will be able to:


a. declare and initialize a string data type;
b. trace and give the output of the string methods used in a program;
and
c. differentiate the characteristics of a string data type from an array of
characters.

Activating Prior Knowledge

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.

There are two ways to create a String object:

1. By string literal: Java String literal is created by using double quotes.


For Example: String s = “Welcome”;
2. By new keyword: Java String is created by using a keyword “new”.
For example: String s = new String(“Welcome”);
It creates two objects (in String pool and in heap) and one reference variable
where the variable ‘s’ will refer to the object in the heap.

Now, let us understand the concept of Java String pool.

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:

Figure 1. The String Pool

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:

char data[] = {‘a’, ‘b’, ‘c’};


String str = new String(data);

4
Unit 4: Java String Methods

Exercise 3.1
Name: _________________________________________ BSIT 2 ___ Score: ___

Declare the following values and variables using Java:

1. Use the variable “days” to declare the days of the week.

String [] days = {“Monday”, “Tuesday”,


“Wednesday”, “Thursday”, “Friday”};

2. Use the variable “name” to declare the letters of your family name.

String name = “Mogado”;

3. Use the variable “contact” to declare the digits of your contact number.

String contact = “09685965121”;

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

11. int compareTo( String anotherString): Compares two string lexicographically.


int out = s1.compareTo(s2); // where s1 ans s2 are
// strings to be compared
This returns difference s1-s2.
If : out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
12. int compareToIgnoreCase( String anotherString): Compares two string
lexicographically, ignoring case considerations.
int out = s1.compareToIgnoreCase(s2);
// where s1 ans s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.

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

Program to illustrate all string methods:

// Java code to illustrate different constructors and methods


// String class.

import java.io.*;
import java.util.*;
class Test
{
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");

// Returns the number of characters in the String.


System.out.println("String length = " + s.length());

// Returns the character at ith index.


System.out.println("Character at 3rd position = "+ s.charAt(3));

// Return the substring from the ith index character


// to end of string
System.out.println("Substring " + s.substring(3));

// Returns the substring from i to j-1 index.


System.out.println("Substring = " + s.substring(2,5));

// Concatenates string2 to the end of string1.


String s1 = "Geeks";
String s2 = "forGeeks";
System.out.println("Concatenated string = " + s1.concat (s2));

// Returns the index within the string


// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " + s4.indexOf ("Share"));

// Returns the index within the string of the


// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " + s4.indexOf ('a',3));

// Checking equality of Strings

8
Unit 4: Java String Methods

Boolean out = "Geeks".equals ("geeks");


System.out.println("Checking Equality " + out);
out = "Geeks".equals ("Geeks");
System.out.println ("Checking Equality " + out);

out = "Geeks".equalsIgnoreCase ("gEeks ");


System.out.println ("Checking Equality " + out);

int out1 = s1.compareTo(s2);


System.out.println("If s1 = s2 " + out);

// 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());

// Trimming the word


String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());

// 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.

String S1 = “It's not a bug, it's a feature”;


String S2 = “Computers have lots of memory but no imagination”;
String S3 = “I just wish my mouth had a backspace key”;

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’));
______________________

Differences between Strings and Character Arrays

The table below compares a string from a character of arrays according to Java
Society (2019).

11
Unit 4: Java String Methods

STRINGS CHARACTER ARRAYS

String refers to a sequence of characters Character Array is a sequential


represented as a single data type. collection of data type char.

Strings are immutable. Character Arrays are mutable.

Built in functions like substring(), charAt() No built-in functions are provided


etc can be used on Strings. in Java for operations on Character
Arrays.

‘+’ 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.

Not preferred for storing passwords in Preferred for storing passwords in


Java. Java.

A String can be converted into Character A Character Array can be converted


Array by using the toCharArray() method into String by passing it into
of String class. a String Constructor.
Eg: String s = “GEEKS”; Eg: char[] a = {‘G’, ‘E’, ‘E’, ‘K’,
char [] ch = s.toCharArray(); ‘S’};
String A = new String(a);

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.

_____ 1. It uses built-in functions like substring (), charAt() etc.

_____ 2. The element is stored contiguously in increasing memory locations.

_____ 3. It is a sequential collection of data type characters.

_____ 4. It is preferred for storing passwords in Java.

_____ 5. It can be converted into string by passing it into a constructor.

_____ 6. It is usually stored in the string constant pool.

_____ 7. This data type is considered as immutable.

_____ 8. The characters are stored in the Heap.

_____ 9. The ‘+’ cannot be used to append in the elements.

_____ 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:

a. How many letters are vowels?

b. How many letters are consonants?

c. Change the sentence in uppercase/lowercase.

d. Count the number of letters and words in the sentence.

2. How could string manipulation affects the programming foundation of an


individual?

14
Unit 4: Java String Methods

Feedback 3 Score: _____


Name: ________________________________________ BSIT 2 _______

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

String str = new String (data);

15
Unit 4: Java String Methods

II. Output Tracing. Trace and give the exact output of the following program
fragments.

String S1 = “Stay safe, stay at home.”;


String S2 = “Salute to all frontliners!”;
String S3 = “We heal as one!”;

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

1. Why is string manipulation important to novice programmers?


______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________

2. Cite your experience/s in transacting to different offices/ agencies relative to


the use and manipulation of your personal information. How these data were
handled and considered?

______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________

17
Unit 4: Java String Methods

Summary Unit

String is a sequence of characters. In java, objects of string are immutable


which means a constant and cannot be changed once created. The java.lang string
class is used to create a string object.
Java String class provides a lot of methods to perform operations
on strings such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc. These methods are important to programmers
in dealing with string data types to easily produce an information necessary in
solving a given problem.
Unlike C/C++ Character arrays and Strings are two different things in Java.
Both Character Arrays and Strings are a collection of characters but are different in
terms of properties.

18
Unit 4: Java String Methods

References

Java Society (2018). Java strings and arrays. Retrieved from


https://www.w3schools.com/java/java_strings.asp
Johari, A. (2020). Java string – string functions in java with examples. Retrieved
from t.ly/hPLW

19

You might also like