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

Strings

The document discusses processing strings in Java using the String, StringBuffer, and StringTokenizer classes. The String class represents fixed strings while StringBuffer represents flexible strings that allow contents to be changed. StringTokenizer can extract tokens from a string. Command-line arguments can also be processed as strings. Key string methods include length(), charAt(), compareTo(), concat(), and substring(). The StringBuffer class offers additional methods like append() to add/modify contents.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Strings

The document discusses processing strings in Java using the String, StringBuffer, and StringTokenizer classes. The String class represents fixed strings while StringBuffer represents flexible strings that allow contents to be changed. StringTokenizer can extract tokens from a string. Command-line arguments can also be processed as strings. Key string methods include length(), charAt(), compareTo(), concat(), and substring(). The StringBuffer class offers additional methods like append() to add/modify contents.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 21

Chapter 7 Strings

Processing strings using the String class, the


StringBuffer class, and the StringTokenizer
class.
Use the String class to process fixed strings.
Use the StringBuffer class to process flexible
strings.
Use the StringTokenizer class to extract tokens
from a string.
Use the command-line arguments.

The String Class

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

String s = new String();

String Comparisons (equals, compareTo)


String Concatenation (concat)
Substrings (substring(index), substring(start, end))
String Length (length())
Retrieving Individual Characters in a string

String Comparisons

equals
String s1 = "Welcome";
String s2 = "welcome";
if (s1.equals(s2))
{ // s1 and s2 have the same contents
if (s1 == s2)

{
// s1 and s2 have the same reference

Strings are immutable


Stringsareimmutable.Thecontentsofa
stringcannotbechanged.Toimprove
efficiencyandsavememory,JavaVirtual
Machinemakesagreatefforttoidentify
theidenticalstringsandstorethemin
thesamememorylocation,butitdoesnot
guaranteethatallofthesamestrings
arestoredinthesamememorylocation.
Therefore,youmustusetheequalsmethod
totestwhethertwostringshavethesame
contents,andthe==operatortotest
whetherthetwostringshavethesame
references(thatis,pointtothesame
memorylocation).

String Comparisons, cont.

compareTo(Object object)
String s1 = "Welcome";
String s2 = "welcome";
if (s1.compare(s2) > 0)
{ // s1 is greater than s2 }
else if (s1.compare(s2 == 0)

{ // s1
else

and s2 have the same reference

// s1 is less than s2

Substrings
String is an immutable class; its values

cannot be changed individually.


String s1 = "Welcome to Java";
String s2 = s1.substring(0,10) + "HTML";

String Concatenation
String s3 = s1.contact(s2);

String s3 = s1 + s2;

Finding String Length


Finding string length using the length()
method:
message = "Welcome";
message.length() (returns 7)

Retrieving Individual Characters


in a String

Do not use message[0]

Use message.charAt(index)

Index starts from 0

String Conversions
Thecontentsofastringcannotbe
changedoncethestringiscreated.
Butyoucanconvertastringtoanew
stringusingthefollowingmethods:
toLowerCase
toUpperCase
trim
replace(oldChar,newChar)

Convert char and numbers to


Strings
TheStringclassprovidesseveral
staticvalueOfmethodsforconvertinga
character,anarrayofcharacters,and
numericvaluestostrings.These
methodshavethesamenamevalueOfwith
differentargumenttypeschar,char[],
double,long,int,andfloat.For
example,toconvertadoublevaluetoa
string,useString.valueOf(5.44).The
returnvalueisstringconsistsof
characters5,.,4,and4.

Example 7.1
Finding Palindromes
Objective:

Checking whether a string


is a palindrome: a string that reads the
same forward and backward.
CheckPalindrome

Run

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 Constructors

public StringBuffer()
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();
strBuf.append("Welcome");
strBuf.append(' ');
strBuf.append("to");
strBuf.append(' ');
strBuf.append("Java");

The StringTokenizer Class


Constructors

StringTokenizer(String s, String
delim, boolean returnTokens)

StringTokenizer(String s, String
delim)

StringTokenizer(String s)

The StringTokenizer Class


Methods

boolean hasMoreTokens()

String nextToken()

String nextToken(String delim)

Example 7.4
Testing StringTokenizer

Objective: Using a string tokenizer, retrieve


words from a string and display them on the
console.

TestStringTokenizer

Run

Command-Line Parameters
class TestMain
{
public static void main(String[] args)
{ ... }
}
java

TestMain arg0 arg1 arg2 ... argn

Processing
Command-Line Parameters
In the main method, get the arguments from
args[0], args[1], ..., args[n], which
corresponds to arg0, arg1, ..., argn in
the command line.

Example 7.5
Using Command-Line Parameters

Objective: Write a program that will perform


binary operations on integers. The program
receives three parameters: an operator and two
integers.
java Calculator + 2 3
Calculator

java Calculator - 2 3

Run

java Calculator / 2 3

You might also like