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

Java String Class

The document discusses the String class in Java. It covers literal strings, immutability, constructors, methods like length(), charAt(), substring(), concatenation, comparisons, replacements, and conversions between strings and numbers. It also discusses the StringTokenizer class for extracting tokens from strings and the StringBuffer class for modifying string content and length.

Uploaded by

Sneha Barnwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Java String Class

The document discusses the String class in Java. It covers literal strings, immutability, constructors, methods like length(), charAt(), substring(), concatenation, comparisons, replacements, and conversions between strings and numbers. It also discusses the StringTokenizer class for extracting tokens from strings and the StringBuffer class for modifying string content and length.

Uploaded by

Sneha Barnwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Java Programming

IT201

1
String CLASS

The objectives of this PPT are:

To explore the concept of String classe

To explore various methods of String class .

2
The String class
• An object of the String class represents a
string of characters.
• The String class belongs to the java.lang
package, which is built into Java.
• Like other classes, String has constructors
and methods.
• Unlike other classes, String has two
operators, + and += (used for concatenation).

Amity University
Literal Strings

• Literal strings are anonymous constant


objects of the String class that are defined as
text in double quotes.
• The string text may include “escape”
characters, for example:
\\ stands for \
\n stands for the newline character

"Biology”, "C:\\jdk1.4\\docs”, "Hello\n"


Amity University
Literal Strings (cont’d)
• don’t have to be constructed:
• can be assigned to String variables.
• can be passed to methods and constructors
as arguments.
• have methods to call:
String fileName = "fish.dat";
button = new JButton("Next slide");
if (”Start".equals(cmd)) ...

Amity University
Immutability
• Once created, a string cannot be changed:
none of its methods changes the string.
• Such types of objects are called immutable.
• Immutable objects are convenient because
two references can point to the same object
safely.
• There is no danger of changing an object
through one reference without the others
being aware of the change.

Amity University
String s1 = "Sun"; String s1 = "Sun";
String s2 = s1; String s2 = new String(s1);
• Advantage: more efficient, no need to copy.
s1 s1 "Sun"
"Sun"
s2 s2 "Sun"

OK Less efficient
and wasteful
Amity University
• Disadvantage:
String s = "sun";less efficient — you need to
create
char cha =new string and throw away
Character.toUpper(s.charAt the old
(0));
s = for
one ch every
+ s.substring
small (1);
change.

s "sun"

'S' + "un"
Amity University
Empty Strings
• An empty string has no characters; its
length is 0.
String s1 = ""; Empty strings
String s2 = new String();

• Not to be confused with an uninitialized


string:
private String errorMsg; errorMsg
is null

Amity University
Constructors

String s1 = new String (); String s1 = "";


• String’s no-args and copy constructors
String s2 = new String (s1); String s2 = s1;

Amity University
Methods
int length ();
— length, charAt
• Returns the number of
characters in the
char charAt string
(k); • Returns the k-th char

Character positions in strings


are numbered starting from 0 Returns:
”Flower".length(); 6
”Wind".charAt (2); ’n'

Amity University
Methods — substring
String s2 = s.substring (i, k); strawberry
– returns the substring of chars in i k
positions from i to k-1

String s2 = s.substring (i);


– returns the substring from the i-th char
to the end Returns:
”raw"
”strawberry".substring (2,5);
"happy"
"unhappy".substring (2);
"" (empty string)
"emptiness".substring (9);
Amity University
Methods — Concatenation
String result = s1 + s2;
– concatenates s1 and s2

String result = s1.concat (s2);


– the same as s1 + s2

result += s3;
– concatenates s3 to result

result += num;
– converts num to String and concatenates
it to result

Amity University
Methods — Find (indexOf)
0 8 11 15

String date ="July 5, 2012 1:28:19 PM";


Returns:
date.indexOf ('J'); 0
date.indexOf ('2'); 8
date.indexOf ("2012"); 8
date.indexOf ('2', 9); 11 (starts searching
at position 9)

date.indexOf ("2020"); -1 (not found)


date.lastIndexOf ('2'); 15
Amity University
Methods — Comparisons
boolean b = s1.equals(s2);
– returns true if the string s1 is equal to s2
boolean b = s1.equalsIgnoreCase(s2);
– returns true if the string s1 matches s2, case-
blind
int diff = s1.compareTo(s2);
– returns the “difference” s1 - s2
int diff = s1.compareToIgnoreCase(s2);
– returns the “difference” s1 - s2, case-blind

Amity University
Methods — Replacements
String s2 = s1.trim ();
– returns a new string formed from s1 by
removing white space at both ends
String s2 = s1.replace(oldCh, newCh);
– returns a new string formed from s1 by
replacing all occurrences of oldCh with newCh
String s2 = s1.toUpperCase();
String s2 = s1.toLowerCase();
– returns a new string formed from s1 by
converting its characters to upper (lower) case

Amity University
Replacements (cont’d)

• Example: To convert s1 to upper case


s1 = s1.toUpperCase();

• A common bug: s1 remains


s1.toUpperCase();
unchanged

Amity University
Numbers to Strings and
Strings to Numbers

• Integer and Double are “wrapper” classes


from java.lang that represent numbers as
objects.
• Integer and Double provide useful static
methods for conversions:
int i;
String s1 = Integer.toString (i); double d;
String s2 = Double.toString (d);
int n = Integer.parseInt (s1);
Thesedouble x =a NumberFormatException
methods throw Double.parseDouble (s2);
if s1/s2 does not represent a valid number.

Amity University
Numbers to Strings
• Three ways to convert a number into a string:
1.
String s = "" + num;
2.
String s = Integer.toString (i); int i;
String s = Double.toString (d); double d;
3.
String s = String.valueOf (num);

Amity University
Numbers to Strings (cont’d)
• The DecimalFormat class can be used
for more controlled conversions of
numbers into strings:

import java.text.DecimalFormat;
...
DecimalFormat money =
new DecimalFormat("0.00"); 56.7899
...
double amt = …;
"56.79"
...
String s = money.format (amt);
Amity University
Character Methods
• java.lang.Character is a class that
represents characters as objects.
• Character has several useful static
methods that determine the type of a
character.
• Character also has methods that convert
a letter to the upper or lower case.

Amity University
Character Methods (cont’d)
if (Character.isDigit (ch)) ...
.isLetter...
.isLetterOrDigit...
.isUpperCase...
.isLowerCase... Whitespace is
.isWhitespace... space, tab,
– return true if ch belongs to thenewline, etc.
corresponding category

Amity University
StringTokenizer
• java.util.StringTokenizer is used to extract
“tokens” from a string.
• Tokens are separated by delimiters (e.g.,
whitespace).
• A tokenizer object is constructed with a given
string as an argument.
• The second optional argument is a string that
lists all delimiters (default is whitespace).

Amity University
StringTokenizer (cont’d)
import java.util.StringTokenizer; Delimiters are
... whitespace
String str = input.readLine();
StringTokenizer q =
new StringTokenizer (str); All delimiters
// or:
// new StringTokenizer (str, ";+ \t, ");
The number of
int n = q.countTokens ();
found tokens
while ( q.hasMoreTokens() )
{
String word = q.nextToken();
...
Amity University
String Buffer Class

• StringBuffer class creates strings of


flexible length that can be modified in
terms of both length and content..
Amity University
Some Common methods of StringBuffer class

s1.setCharAt(n ,’x’) : Modifies the nth character to x


s1.append(s2) : Appends the string s2 to s1 at end
s1.insert(n,s2) : Insert the string s2 at the position
n of the string s1.
s1.setLength(n) : Sets the length of the string s1 to n
If n<s1.length s1 is truncated.
If n> s1.length() zeros are added to s1

Amity University

You might also like