0% found this document useful (0 votes)
1 views26 pages

Java Lec 3 Strings

The document provides an overview of the String class in Java, detailing its properties, methods, and how to manipulate strings. It explains string construction, immutability, comparison, and conversion, as well as introduces the StringBuffer class for mutable strings. Additionally, it includes examples and practice problems related to string operations.
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)
1 views26 pages

Java Lec 3 Strings

The document provides an overview of the String class in Java, detailing its properties, methods, and how to manipulate strings. It explains string construction, immutability, comparison, and conversion, as well as introduces the StringBuffer class for mutable strings. Additionally, it includes examples and practice problems related to string operations.
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

The String Class

Strings
❑A string is a sequence of characters
❑ Strings are objects of the String class

❑ String constants:
"Hello, World!"
❑ String variables:
String message = "Hello, World!";
❑ String length:
int n = [Link]();
❑ Empty string:
""
Constructing a String:

String message = "Welcome to Java!”

String is an Object in Java.


Constructing Strings
String newString = new String(message);

String message = new String("Welcome to Java!");

Since strings are used frequently, Java provides a shorthand


notation for creating a string:

String message = "Welcome to Java!";


String

+String()
+String(value: String)
+String(value: char[])
+charAt(index: int): char
+compareTo(anotherString: String): int
+compareToIgnoreCase(anotherString: String): int
+concat(anotherString: String): String
+endsWithSuffixe(suffix: String): boolean
+equals(anotherString: String): boolean
+equalsIgnoreCase(anotherString: String): boolean
+indexOf(ch: int): int
+indexOf(ch: int, fromIndex: int): int
+indexOf(str: String): int
+indexOf(str: String, fromIndex: int): int
+intern(): String
+regionMatches(toffset: int, other: String, offset: int, len: int): boolean
+length(): int
+replace(oldChar: char, newChar: char): String
+startsWith(prefix: String): boolean
+subString(beginIndex: int): String
+subString(beginIndex: int, endIndex: int): String
+toCharArray(): char[]
+toLowerCase(): String
+toString(): String
Retrieving Individual Characters
in a String
❑ Do not use message[0]
❑ Use [Link](index)
❑ Index starts from 0

Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message W e l c o m e t o J a v a

[Link](0) [Link]() is 15 [Link](14)


String Concatenation
String s3 = [Link](s2);

String s3 = s1 + s2;
Extracting Substrings

String s1 = "Welcome to Java";


String s2 = [Link](0, 11) + "HTML";

Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message W e l c o m e t o J a v a

[Link](0, 11) [Link](11)


Strings Are Immutable
A String object is immutable, whose contents cannot
be changed.
To improve efficiency and save memory, Java Virtual
Machine stores two String objects into the same
object, if the two String objects are created with the
same string literal using the shorthand notation.
Therefore, the shorthand notation is preferred to create
strings.
String ==
String s = "Welcome to Java!";
String s1 = new String("Welcome to Java!");
String s2 = [Link]();
[Link]("s1 == s is " + (s1 == s));
[Link]("s2 == s is " + (s2 == s));
[Link]("s1 == s2 is " + (s1 == s2));
displays
s1 == s is false
s2 == s is true
s1 == s2 false
String Comparisons: equals

String s1 = "Welcome";
String s2 = “Welcome";

if ([Link](s2)){
// s1 and s2 have the same contents
}
if (s1 == s2) {
// s1 and s2 have the same reference
}
compareTo(Object object)
if ([Link](s2) > 0) {
// s1 is greater than s2
}
String Conversions
The contents of a string cannot be changed once
the string is created. But you can convert a string
to a new string using the following methods:

❑ toLowerCase
❑ toUpperCase
❑ trim
❑ replace(oldChar, newChar)
Finding a Character or a
Substring in a String
"Welcome to Java!".indexOf('W')) returns 0.
"Welcome to Java!".indexOf('x')) returns -1.
"Welcome to Java!".indexOf('o', 5)) returns 9.
"Welcome to Java!".indexOf("come")) returns 3.
"Welcome to Java!".indexOf("Java", 5)) returns 11.
"Welcome to Java!".indexOf("java", 5)) returns -1.
Convert Character and Numbers
to Strings
valueOf methods for converting a character, an
array of characters, and numeric values to strings.
These methods have the same name valueOf with
different argument types char, char[], double, long,
int, and float.

Convert a double value to a String


[Link](5.44).
The Character Class
Character

+Character(value: char)
+charValue(): char
+compareTo(anotherCharacter: Character): int
+equals(anotherCharacter: Character): boolean
+isDigit(ch: char): boolean
+isLetter(ch: char): boolean
+isLetterOrDigit(ch: char): boolean
+isLowerCase(ch: char): boolean
+isUpperCase(ch: char): boolean
+toLowerCase(ch: char): char
+toUpperCase(ch: char): char
Examples: Given a Character
Object with value 'b'
[Link](new Character('a')) returns 1
[Link](new Character('b')) returns 0
[Link](new Character('c')) returns -1
[Link](new Character('d') returns –2
[Link](new Character('b')) returns true
[Link](new Character('d')) returns false
Counting Each Letter in a String
Write a program that counts the number of
occurrence of each letter in a string. Assume the
letters are not case-sensitive.
String and String pools
What will be the output for :
String s1 = new String("Welcome to Java!");
String s1 = new String("Welcome to Java!"); String s = "Welcome to Java!";
String s = "Welcome to Java!"; String s2 = [Link]();
String s2 = [Link](); [Link]("s1 == s is " + (s1 == s));
[Link]("s1 == s is " + (s1 == s)); [Link]("s2 == s is " + (s2 == s));
[Link]("s1 == s2 is " + (s1 == s2));
[Link]("s2 == s is " + (s2 == s));
[Link]("s1 == s2 is " + (s1 == s2));
The StringBuffer Class
The StringBuffer class is an alternative to the
String class. In general, a string buffer can be
used wherever a string is used.

StringBuffer is more flexible than String. You


can add, insert, or append new contents
into a string buffer. However, the value of
a string is fixed once the string is created.
StringBuffer

+append(data: char[]): StringBuffer


+append(data: char[], offset: int, len: int): StringBuffer
+append(v: aPrimitiveType): StringBuffer
+append(str: String): StringBuffer
+capacity(): int
+charAt(index: int): char
+delete(startIndex: int, endIndex: int): StringBuffer
+deleteCharAt(int index): StringBuffer
+insert(index: int, data: char[], offset: int, len: int): StringBuffer
+insert(offset: int, data: char[]): StringBuffer
+insert(offset: int, b: aPrimitiveType): StringBuffer
+insert(offset: int, str: String): StringBuffer
+length(): int
+replace(int startIndex, int endIndex, String str): StringBuffer
+reverse(): StringBuffer
+setCharAt(index: int, ch: char): void
+setLength(newLength: int): void
+substring(start: int): StringBuffer
+substring(start: int, end: int): StringBuffer
StringBuffer Constructors
❑ publicStringBuffer()
No characters, initial capacity 16 characters.
❑ public StringBuffer(int length)
No characters, initial capacity specified by
the length argument.
❑ public StringBuffer(String str)
Represents the same sequence of characters
as the string argument. Initial capacity 16
plus the length of the string argument.
Appending New Contents
into a String Buffer
StringBuffer strBuf = new StringBuffer();
[Link]("Welcome");
[Link](' ');
[Link]("to");
[Link](' ');
[Link]("Java");
Self Check
❑ Assuming the String variable s holds
the value "Agent", what is the effect of
the assignment s = s +
[Link]()?
❑ Assuming the String variable river
holds the value "Mississippi", what
is the value of [Link](1,
2)? Of [Link](2,
[Link]() - 3)?
Answers
❑ s is set to the string Agent5
❑ The strings "i" and "ssissi"
String practice problem
Given Strings s1, s2, s3, Give code using the String
class methods
• Order the strings Lexicographically Gr 1-4
• Checking whether a string is a palindrome Gr 5-8
• Convert s1into substrings by breaking where there
are spaces Gr 9-12
• Create a string from s1 inserting "ab" wherever
there is a 'a' Gr 13-16
• Set a boolean array barry[] based on whether
these strings start with "at". Gr 17-20

You might also like