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

CSE 1004 - Module 6 - Strings

This document discusses strings in Java. It is a module on strings from a CSE 1004 problem solving using Java course taught by Mrs. Daphna Chacko. The document covers string declaration, initialization, types of strings, built-in string methods like length(), charAt(), trim(), concat(), conversion methods, escape sequences, immutability, string pool, reading/writing strings, wrapper classes, converting between strings and numbers, comparing strings, finding substrings, the replace() method, and regionMatches().

Uploaded by

anuj
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)
49 views

CSE 1004 - Module 6 - Strings

This document discusses strings in Java. It is a module on strings from a CSE 1004 problem solving using Java course taught by Mrs. Daphna Chacko. The document covers string declaration, initialization, types of strings, built-in string methods like length(), charAt(), trim(), concat(), conversion methods, escape sequences, immutability, string pool, reading/writing strings, wrapper classes, converting between strings and numbers, comparing strings, finding substrings, the replace() method, and regionMatches().

Uploaded by

anuj
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/ 26

CSE 1004: Problem solving using java

module 6: strings
Faculty: Mrs Daphna Chacko, Assistant Professor, SCOPE.

1
Introduction
➢ A string literal is a series of characters that is enclosed in double quotes. For eg,
“Java”
➢ String is a sequence of characters
➢ In Java, strings are objects of the String class.
➢ The String type is not a primitive type. It is known as a reference type.
➢ The variable declared by a reference type is known as a reference variable that
references an object.
➢ String str = "Java Programming";
○ Here str is an object of the class String. i.e, str is a reference variable that references a String object
with contents Java Programming.

Daphna Chacko CSE1004 2


Declaration and initialisation of strings
● The following statement declares str to be the name for a String variable:
○ String str;
● The following statement sets the value of str to the String value "Hello!":
○ str = "Hello!";
● These two statements are often combined into one, as follows:
○ String str = "Hello!";
● Strings can also be created using new keyword
○ String s = new String (“Hello”); Constructor

A constructor in Java is a special method that is used to initialize objects. A constructor


has the same name as the class and is invoked when an object of a class is created. There
can be overloaded constructor methods.

Daphna Chacko CSE1004 3


Types of strings
➢ A string can have any number of characters.

➢ A string can even have zero characters. Such a string is called the empty string and is
written as a pair of adjacent double quotes ("").
➢ The string " " is not empty: It consists of one blank character
Daphna Chacko CSE1004 4
Some in built methods in String class

Daphna Chacko CSE1004 5


length()
● Returns the number of characters in a string
● For example, String str = “Java”;
System.out.println(str.length());
would display the value 4.
● Spaces, special symbols, and repeated characters are all counted when computing the
length of a string
● Java allows the string literal to refer directly to string methods without creating new
variables.
● Thus, "Java".length() is correct and returns 4.
● Note that ""denotes an empty string and "".length() is 0
Daphna Chacko CSE1004 6
charAt(index)
● This method is used to retrieve a character at a particular position in a string.
● Positions, or indices, in a string is between 0 and s.length()–1.
● To avoid the out of bounds exception avoid using an index beyond s.length() – 1
● For example, String str = “Java uses OOP”;
char ch = str.charAt(5); stores ‘u’ in ch.
● A part of a string is known as substring.
● For example, ‘uses’ is a substring of the string “Java uses OOP” and begins at
index 5

Daphna Chacko CSE1004 7


trim()
● The trim() method returns a new string by eliminating whitespace characters from
both ends of the string.

● Any characters that are not visible when displayed are collectively known as
whitespace. Such characters include blanks, tabs, and new-line characters.

● The characters ' ', \t, \f, \r, or \n are known as whitespace characters.

For example, "\t Hello World \n".trim() returns a new string Hello World.

Daphna Chacko CSE1004 8


concat(s)
● Returns a new string having the same characters as the string invoking this method,
concatenated with the characters in s.
● For example, Let s1 ans s2 be strings containing “Hello” and “Everyone”
respectively. String s3 = s1.concat(s2); will store HelloEveryone in s3
● The above result can be obtained by using the + operator instead of concat(). Thus the
above statement is equivalent to String s3 = s1+ s2;
● + operator can also concatenate a number with a string. Eg,String s= 3+”persons”
stores “3persons” in s
● At least one of the operands must be a string in order for concatenation to take place.
● If neither of the operands is a string, the plus sign (+) is the addition operator that
adds two numbers

Daphna Chacko CSE1004 9


Converting Strings

● toLowerCase() method returns a new string with all lowercase letters

● toUpperCase() method returns a new string with all uppercase letters.

○ For example, "Welcome".toLowerCase() returns a new string welcome.

○ "Welcome".toUpperCase() returns a new string WELCOME.

Daphna Chacko CSE1004 10


Escape sequences
● Escape sequences or escape characters are special characters that are indicated with a backslash.
● They escape from the usual meaning of a character, such as the usual meaning of the double
quote.
● Each escape sequence represents one character, even though it is written as two symbols.
● Following are some of the escape sequences:

○ "This is \"Java\" class "


○ "Abc\\def"
○ "The motto is\nGo for it!"
○ char singleQuote = '\'';

Daphna Chacko CSE1004 11


Strings are immutable!!
● Values of objects of type String cannot be changed
● Hence none of the in built methods changes the value of a String object.
● Although the value of a String object, such as "Pradesh", cannot be changed,
the value of a String variable can be changed i.e. a variable of String type can
store reference to any String object/literal.
○ String name = "Pradesh";

○ name = "Andhra " + name; // The value of the string “Pradesh’ is not changed

Daphna Chacko CSE1004 12


String Pool
● String Pool is a storage area in Java heap which stores a pool of string literals
● Each time a string literal is created, the JVM checks the string literal pool first.
● If the string already exists in the string pool, a reference to the pooled instance returns.
● If the string does not exist in the pool, a new String object is initialized and is placed in the pool.

Daphna Chacko CSE1004 13


Reading from console using Scanner class
● To read a string that ends with a whitespace character from the console, invoke the
next() method i.e. sc.next()

● To read an entire line of text i.e, a string that ends with the Enter key pressed, invoke
the nextLine() method i.e. sc.nextLine()

● To read a character from the console, use the nextLine() method to read a string and
then invoke the charAt(0) method on the string to return a character i.e.,
sc.nextLine().charAt(0)

Daphna Chacko CSE1004 14


Wrapper classes in Java
● A Wrapper class is a class whose object wraps or contains primitive data types.
● Autoboxing is used to convert primitive data types into corresponding objects.
● Unboxing is used to convert the Wrapper class object into corresponding primitive data types.
● Wrapper classes are part of the lang package

Daphna Chacko CSE1004 15


Conversion between Strings and Numbers
● A number can be converted into a string, by using the string concatenation
operator:
○ String s = number + "";

● To convert a string into an int value, use the Integer.parseInt() method


○ int intValue = Integer.parseInt(intString); where intString is a numeric string such as "123".

● To convert a string into a double value, use the Double.parseDouble() method:


○ double doubleValue = Double.parseDouble(doubleString); where doubleString is a numeric
string such as "123.45".

● If the string is not a numeric string, the conversion would cause a runtime error.

Daphna Chacko CSE1004 16


Comparing Strings

Daphna Chacko CSE1004 17


Finding a character or a substring in a string

Daphna Chacko CSE1004 18


Obtaining substrings from strings

Daphna Chacko CSE1004 19


replace(old,new)
● This method returns a string derived from this string by replacing every
occurrence of the character in old with the character in new.
○ String str="Dear";
○ String s=str.replace('a','e');
● The contents of the original string is not changed whereas a new string is
created.

Daphna Chacko CSE1004 20


regionMatches( )
● regionMatches(int ind, String str, int strIndex, int len)
● Returns true if the substring str starting at strIndex and of length specified by len is same
as the substring of this String object starting at ind and having the same length

● regionMatches(boolean ignoreCase, int ind, String str, int strIndex, int len)
● Returns true if the substring str starting at strIndex and of length specified by len is same
as the substring of this String object starting at ind and having the same length. Here the
region is compared regardless of case if ignoreCase is true
○ String source = "hello world";
○ String anotherString = "World of java";
○ System.out.println(source.regionMatches(6, anotherString, 0, 5));
○ System.out.println(source.regionMatches(true,6, anotherString, 0, 5));

Daphna Chacko CSE1004 21


String arrays
● An array of Strings creates an array where each element is a reference to a String
object.
● A String array can be declared as:
○ String[] nameList = new String[5];
○ nameList[0]= “Amanda Green”;
○ nameList[1]= “Vijay Arora”;
○ nameList[2]= new String (“Sheila Mann);
○ nameList[2]= “Rohit Sharma”;
○ nameList[0]= “Mandy Johnson”;

Daphna Chacko CSE1004 22


Some methods in Math class
● max(a, b)and min(a, b) : Returns the maximum or minimum of two
parameters.
– Math.max(2, 3) returns 3
– Math.max(2.5, 3) returns 3.0
– Math.min(2.5, 3.6) returns 2.5
● abs(a) : Returns the absolute value of the parameter.
– Math.abs(-2) returns 2
– Math.abs(-2.1) returns 2.1
● random() : Returns a random double value in the range [0.0, 1.0).

Daphna Chacko CSE1004 23


Summary
In this module we learned:
➔ Strings
➔ Declaration and initialisation of strings
➔ String Pools
➔ Methods provided by String class
➔ Methods provided by Math class

Daphna Chacko CSE1004 24


References
1. “Introduction to Java Programming”, 10th Edition, Daniel Liang.
2. “Introduction to problem solving and programming”, 6th Edition, Walter
Savitch.
3. “Java Programming”,4th Edition, D.S. Malik

NB: Images are adapted from Internet

Daphna Chacko CSE1004 25


Learn to think in algorithmic way… It makes life simpler!!!

All the best to be excellent programmers….

Daphna Chacko CSE1004 26

You might also like