liang,introduction to java programming,revised by dai-kaiyu 1 chapter 7 strings some people hear...

72
Liang,Introduction to Java Programming,revised by D ai-kaiyu 1 Chapter 7 Strings Prerequisitesfor PartII Chapter6 O bjectsand Classes Chapter7 Strings Chapter8 Inheritance and Polym orphism Chapter5 A rrays Chapter9 A bstractClassesand Interfaces Chapter10 O bject-O riented M odeling Chapter11 G etting Started w ith G U IProgram ming Chapter12 Event-D riven Program ming Chapter15 Exceptionsand A ssertions Chapter16 Sim ple Inputand O utput Y ou can coverExceptionsand I/O afterChapter8 Y ou can coverG U IafterChapter8 Some people hear their own inner voices with great clearness, they live by what they hear…

Upload: morgan-ray

Post on 14-Jan-2016

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu1

Chapter 7 Strings

Prerequisites for Part II

Chapter 6 Objects and Classes

Chapter 7 Strings

Chapter 8 Inheritance and Polymorphism

Chapter 5 Arrays

Chapter 9 Abstract Classes and Interfaces

Chapter 10 Object-Oriented Modeling

Chapter 11 Getting Started with GUI Programming

Chapter 12 Event-Driven Programming

Chapter 15 Exceptions and Assertions

Chapter 16 Simple Input and Output

You can cover Exceptions and I/O after Chapter 8

You can cover GUI after Chapter 8

Some people hear their own inner voices with great clearness, they live by what they hear…

Page 2: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu2

Objectives To use the String class to process fixed strings (§7.2). To use the Character class to process a single character (§7.3). To use the StringBuffer class to process flexible strings (§7.4). To use the StringTokenizer class to extract tokens from a string

(§7.5). To know the differences among the String, StringBuffer, and

StringTokenizer classes (§7.2-7.5). To use the JDK 1.5 Scanner class for console input and scan

tokens using words as delimiters (§7.6). To input primitive values and strings from the keyboard using

the Scanner class (§7.7). To learn how to pass strings to the main method from the

command line (§7.8).

Page 3: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu3

Introduction

String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer

Page 4: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu4

Fundamentals of Characters and Strings

Characters “Building blocks” of Java source programs

String Series of characters treated as single unit May include letters, digits, etc. Object of class String

Page 5: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu5

The String Class

Constructing a String: String message = "Welcome to Java“; String message = new String("Welcome to Java“); String s = new String();

Obtaining String length and Retrieving Individual Characters in a string String

String Concatenation (concat) Substrings (substring(index), substring(start, end)) Comparisons (equals, compareTo) String Conversions Finding a Character or a Substring in a String Conversions between Strings and Arrays Converting Characters and Numeric Values to Strings

Page 6: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu6

String

+String()

+String(value: String)

+String(value: char[])

+charAt(index: int): char

+compareTo(anotherString: String): int

+compareToIgnoreCase(anotherString: String): int

+concat(anotherString: String): String

+endsWith(suffix: String): boolean

+equals(anotherString: String): boolean

+equalsIgnoreCase(anotherString: String): boolean

+getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): void

+indexOf(ch: int): int

+indexOf(ch: int, fromIndex: int): int

+indexOf(str: String): int

+indexOf(str: String, fromIndex: int): int

+lastIndexOf(ch: int): int

+lastIndexOf(ch: int, fromIndex: int): int

+lastIndexOf(str: String): int

+lastIndexOf(str: String, fromIndex: int): int

+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

+toUpperCase(): String

+trim(): String

+copyValueOf(data: char[]): String

+valueOf(c: char): String

+valueOf(data: char[]): String

+valueOf(d: double): String

+valueOf(f: float): String

+valueOf(i: int): String

+valueOf(l: long): String

Constructs an empty string

Constructs a string with the specified string literal value

Constructs a string with the specified character array

Returns the character at the specified index from this string

Compares this string with another string

Compares this string with another string ignoring case

Concat this string with another string

Returns true if this string ends with the specified suffix

Returns true if this string is equal to anther string

Checks if this string equals anther string ignoring case

Copies characters from this string into the destination character array

Returns the index of the first occurrence of ch

Returns the index of the first occurrence of ch after fromIndex

Returns the index of the first occurrence of str

Returns the index of the first occurrence of str after fromIndex

Returns the index of the last occurrence of ch

Returns the index of the last occurrence of ch before fromIndex

Returns the index of the last occurrence of str

Returns the index of the last occurrence of str before fromIndex

Returns true if the specified subregion of this string exactly matches the specified subregion of the string argument

Returns the number of characters in this string

Returns a new string with oldChar replaced by newChar

Returns true if this string starts with the specified prefix

Returns the substring from beginIndex

Returns the substring from beginIndex to endIndex

Returns a char array consisting characters from this string

Returns a new string with all characters converted to lowercase

Returns a new string with itself

Returns a new string with all characters converted to uppercase

Returns a string with blank characters trimmed on both sides

Returns a new string consisting of the char array data

Returns a string consisting of the character c

Same as copyValueOf(data: char[]): String

Returns a string representing the double value

Returns a string representing the float value

Returns a string representing the int value

Returns a string representing the long value

Page 7: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu7

Constructing Strings

String newString = new String(stringLiteral);

 

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

Since strings are used frequently, Java provides a shorthand initializer for creating a string:

String message = "Welcome to Java";

Page 8: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

8

Liang,Introduction to Java Programming,revised by Dai-kaiyu

1 // StringConstructors.java2 // This program demonstrates the String class constructors.3 4 // Java extension packages5 import javax.swing.*;6 7 public class StringConstructors {8 9 // test String constructors10 public static void main( String args[] )11 {12 char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ',13 'd', 'a', 'y' };14 byte byteArray[] = { ( byte ) 'n', ( byte ) 'e', 15 ( byte ) 'w', ( byte ) ' ', ( byte ) 'y', 16 ( byte ) 'e', ( byte ) 'a', ( byte ) 'r' };17 18 StringBuffer buffer;19 String s, s1, s2, s3, s4, s5, s6, s7, output;20 21 s = new String( "hello" );22 buffer = new StringBuffer( "Welcome to Java Programming!" );23 24 // use String constructors25 s1 = new String();26 s2 = new String( s );27 s3 = new String( charArray );28 s4 = new String( charArray, 6, 3 );29 s5 = new String( byteArray, 4, 4 );30 s6 = new String( byteArray );31 s7 = new String( buffer );32

Constructor copies StringBuffer

Constructor copies byte-array subset

Constructor copies byte array

Constructor copies character-array subset

Constructor copies character array

Constructor copies String

String default constructor instantiates empty string

Page 9: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

9

Liang,Introduction to Java Programming,revised by Dai-kaiyu

33 // append Strings to output34 output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 +35 "\ns4 = " + s4 + "\ns5 = " + s5 + "\ns6 = " + s6 +36 "\ns7 = " + s7;37 38 JOptionPane.showMessageDialog( null, output,39 "Demonstrating String Class Constructors",40 JOptionPane.INFORMATION_MESSAGE );41 42 System.exit( 0 );43 }44 45 } // end class StringConstructors

Page 10: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu10

Strings Are Immutable

A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string?

String s = "Java";

s = "HTML";

s: String

String object for "Java"

s

After executing String s = "Java";

After executing s = "HTML";

: String

String object for "Java"

s

s: String

String object for "HTML"

Contents cannot be changed

This string object is now unreferenced

Page 11: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu11

Trace Code

String s = "Java";

s = "HTML";

: String

String object for "Java"

s

After executing String s = "Java";

After executing s = "HTML";

: String

String object for "Java"

: String

String object for "HTML"

Contents cannot be changed

This string object is now unreferenced

s

Page 12: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu12

Trace Code

String s = "Java";

s = "HTML";

: String

String object for "Java"

s

After executing String s = "Java";

After executing s = "HTML";

: String

String object for "Java"

: String

String object for "HTML"

Contents cannot be changed

This string object is now unreferenced

s

Page 13: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu13

Canonical Strings

Since strings are immutable, to improve efficiency and save memory, the JVM stores two String objects in the same object if they were created with the same string literal using the shorthand initializer. Such a string is referred to as a canonical string. You can also use a String object’s intern method to return a canonical string, which is the same string that is created using the shorthand

initializer.

Page 14: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu14

Examples

display  s1 == s is false s2 == s is true s == s3 is true

String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; System.out.println("s1 == s is " + (s1 == s)); System.out.println("s2 == s is " + (s2 == s)); System.out.println("s == s3 is " + (s == s3));

: String

Canonical string object for "Welcome to Java"

: String

A string object for "Welcome to Java"

Page 15: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu15

Examples

display  s1 == s is false s2 == s is true s == s3 is true

A new object is created if you use the new operator.

If you use the string initializer, no new object is created if the interned object is already created.

String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; System.out.println("s1 == s is " + (s1 == s)); System.out.println("s2 == s is " + (s2 == s)); System.out.println("s == s3 is " + (s == s3));

: String

Interned string object for "Welcome to Java"

: String

A string object for "Welcome to Java"

s

s1

s2

s3

Page 16: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu16

Trace Code String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java";

: String

Interned string object for "Welcome to Java"

s

Page 17: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu17

Trace Code String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java";

: String

Interned string object for "Welcome to Java"

: String

A string object for "Welcome to Java"

s

s1

Page 18: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu18

Trace Code String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java";

: String

Interned string object for "Welcome to Java"

: String

A string object for "Welcome to Java"

s

s1

s2

Page 19: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu19

Trace Code String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java";

: String

Interned string object for "Welcome to Java"

: String

A string object for "Welcome to Java"

s

s1

s2

s3

Page 20: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu20

String Method intern

String comparisons Slow operation Method intern improves this performance

Returns reference to String Guarantees reference has same contents as original String

To create a constant object in the memory(const pool) with the same content with the original object. Then it is enough to just compare their references ,not concret content.

Page 21: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu21

If the String is changed?

Class String is immutable The difference between

String s1 = new String(“I am string”); String s2 =new String(“I am string”);

String s1 = “I am string”; String s2 = “I am string”;

What about

String s = "Hello";s = s + " world!";

== ?

Equals ?

If we always change the String, then it will bring bigger memory, change

to StringBuffer

Page 22: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu22

Finding String Length

Finding string length using the length() method:

message = "Welcome";

message.length() (returns 7)

Page 23: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu23

Retrieving Individual Characters in a String

Do not use message[0]

Use message.charAt(index)

Index starts from 0

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

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

message

Indices

message.charAt(0) message.charAt(14) message.length() is 15

StringIndexOutOfBoundsException

Page 24: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu24

String Concatenation

String s3 = s1.concat(s2);

String s3 = s1 + s2;

s1 + s2 + s3 + s4 + s5 same as

(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);

Page 25: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu25

Extracting Substrings

String is an immutable class; its valuescannot be changed individually.

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

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

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

message

Indices

message.substring(0, 11) message.substring(11)

Page 26: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu26

String Comparisons equals

String s1 = new String("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 }

Demo TestString.java

Page 27: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu27

String Comparisons, cont. compareTo(Object object)

String s1 = new String("Welcome“);String s2 = "welcome";

if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents } else // s1 is less than s2

Page 28: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu28

String Comparisons, cont.

equalsIgnoreCaseregionMatches: compares portions of two

strings for equalitystr.startsWith(prefix)

str.endsWith(suffix)

Page 29: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

29

Liang,Introduction to Java Programming,revised by Dai-kaiyu

1 // StringCompare.java2 // This program demonstrates the methods equals, 3 // equalsIgnoreCase, compareTo, and regionMatches 4 // of the String class.5 6 // Java extension packages7 import javax.swing.JOptionPane;8 9 public class StringCompare {10 11 // test String class comparison methods12 public static void main( String args[] )13 {14 String s1, s2, s3, s4, output;15 16 s1 = new String( "hello" );17 s2 = new String( "good bye" );18 s3 = new String( "Happy Birthday" );19 s4 = new String( "happy birthday" );20 21 output = "s1 = " + s1 + "\ns2 = " + s2 +22 "\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n";23 24 // test for equality25 if ( s1.equals( "hello" ) )26 output += "s1 equals \"hello\"\n";27 else28 output += "s1 does not equal \"hello\"\n"; 29 30 // test for equality with ==31 if ( s1 == "hello" )32 output += "s1 equals \"hello\"\n";33 else34 output += "s1 does not equal \"hello\"\n";35

Method equals tests two objects for equality using

lexicographical comparison

Equality operator (==) tests if both references refer to same

object in memory

Compare:s1 = new String(“hello”);

s1 = “hello”

Page 30: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

30

Liang,Introduction to Java Programming,revised by Dai-kaiyu

36 // test for equality (ignore case)37 if ( s3.equalsIgnoreCase( s4 ) )38 output += "s3 equals s4\n";39 else40 output += "s3 does not equal s4\n";41 42 // test compareTo43 output +=44 "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) +45 "\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) +46 "\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) +47 "\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) +48 "\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) +49 "\n\n";50 51 // test regionMatches (case sensitive)52 if ( s3.regionMatches( 0, s4, 0, 5 ) )53 output += "First 5 characters of s3 and s4 match\n";54 else55 output +=56 "First 5 characters of s3 and s4 do not match\n";57 58 // test regionMatches (ignore case)59 if ( s3.regionMatches( true, 0, s4, 0, 5 ) )60 output += "First 5 characters of s3 and s4 match";61 else62 output +=63 "First 5 characters of s3 and s4 do not match";64

Test two objects for equality, but ignore case

of letters in String

Method compareTo compares String objects

Method regionMatches compares portions of two

String objects for equality

Ignore case

Page 31: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

31

Liang,Introduction to Java Programming,revised by Dai-kaiyu

65 JOptionPane.showMessageDialog( null, output,66 "Demonstrating String Class Constructors",67 JOptionPane.INFORMATION_MESSAGE );68 69 System.exit( 0 );70 }71 72 } // end class StringCompare

Page 32: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu32

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)

Page 33: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu33

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.

"Welcome to Java".lastIndexOf('a') returns 14.

Page 34: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu34

Conversion between String and Arrays

toCharArray()char [] chars = “Java”.toCharArray();

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)char[] dst = {‘J’, ’A’, ‘V’, ‘A’, ‘1’, ‘3’, ‘0’, ‘1’};“CS3720”.getChars(2 , 6, dst, 4);

Dst = {‘J’, ’A’, ‘V’, ‘A’, ‘3’, ‘7’, ‘2’, ‘0’}

Page 35: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu35

Convert Character and Numbers to Strings

The String class provides several static 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. For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.

Page 36: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

36

Liang,Introduction to Java Programming,revised by Dai-kaiyu

1 // Fig. 10.10: StringValueOf.java2 // This program demonstrates the String class valueOf methods.3 4 // Java extension packages5 import javax.swing.*;6 7 public class StringValueOf {8 9 // test String valueOf methods10 public static void main( String args[] )11 {12 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };13 boolean b = true;14 char c = 'Z';15 int i = 7;16 long l = 10000000;17 float f = 2.5f;18 double d = 33.333;19 20 Object o = "hello"; // assign to an Object reference21 String output;22 23 output = "char array = " + String.valueOf( charArray ) +24 "\npart of char array = " +25 String.valueOf( charArray, 3, 3 ) +26 "\nboolean = " + String.valueOf( b ) +27 "\nchar = " + String.valueOf( c ) +28 "\nint = " + String.valueOf( i ) +29 "\nlong = " + String.valueOf( l ) + 30 "\nfloat = " + String.valueOf( f ) + 31 "\ndouble = " + String.valueOf( d ) + 32 "\nObject = " + String.valueOf( o );33

static method valueOf of class String returns String

representation of various types

Page 37: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

37

Liang,Introduction to Java Programming,revised by Dai-kaiyu

34 JOptionPane.showMessageDialog( null, output,35 "Demonstrating String Class valueOf Methods",36 JOptionPane.INFORMATION_MESSAGE );37 38 System.exit( 0 );39 }40 41 } // end class StringValueOf

Page 38: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu38

Example 7.1Finding Palindromes

Objective: Checking whether a string is a palindrome: a string that reads the same forward and backward.

CheckPalindromeCheckPalindrome RunRun

Page 39: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu39

Character Class Examples

Treat primitive variables as objects Type wrapper classes

Boolean Character Double Float Byte Short Integer Long

We examine class Character

Page 40: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu40

Type-Wrapper Classes for Primitive Types

Type-wrapper class Each primitive type has one

Character, Byte, Integer, Short, Boolean, Long,

Float, Double, etc. Enable to represent primitive as Object

Primitive data types can be processed polymorphically Declared as final,inherited from Number(except for

Boolean, Character) Many methods are declared static

Page 41: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu41

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

Constructs a character object with char value

Returns the char value from this object

Compares this character with another

Returns true if this character equals to another

Returns true if the specified character is a digit

Returns true if the specified character is a letter

Returns true if the character is a letter or a digit

Returns true if the character is a lowercase letter

Returns true if the character is an uppercase letter

Returns the lowercase of the specified character

Returns the uppercase of the specified character

Page 42: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu42

Examples

Character charObject = new Character('b');

charObject.charValue() returns ‘b’;charObject.compareTo(new Character('a')) returns 1charObject.compareTo(new Character('b')) returns 0charObject.compareTo(new Character('c')) returns -1charObject.compareTo(new Character('d') returns –2charObject.equals(new Character('b')) returns truecharObject.equals(new Character('d')) returns false

Page 43: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu43

Examples

Suppose c is variable of a char type• Character.isDefined( c ) • Character.isDigit( c )

Character.isJavaIdentifierStart( c ) Character.isJavaIdentifierPart( c )

• Character.isLetter( c ) • Character.isLetterOrDigit( c ) • Character.isLowerCase( c ) • Character.isUpperCase( c )• Character.toUpperCase( c )• Character.toLowerCase( c )

Page 44: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu44

Example 7.2Counting Each Letter in a String

This example gives a program that counts the number of occurrence of each letter in a string. Assume the letters are not case-sensitive.

CountEachLetterCountEachLetter RunRun

Page 45: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu45

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 contentsinto a string buffer. However, the value ofa String object is fixed once the string is created.

Page 46: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu46

StringBuffer

+StringBuffer()

+StringBuffer(capacity: int)

+StringBuffer(str: String)

+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(startIndex: int): String

+substring(startIndex: int, endIndex: int): String

Constructs an empty string buffer with capacity 16

Constructs a string buffer with the specified capacity

Constructs a string buffer with the specified string

Appends a char array into this string buffer

Appends a subarray in data into this string buffer

Appends a primitive type value as string to this buffer

Appends a string to this string buffer

Returns the capacity of this string buffer

Returns the character at the specified index

Deletes characters from startIndex to endIndex

Deletes a character at the specified index

Inserts a subarray of the data in the array to the buffer at the specified index

Inserts data to this buffer at the position offset

Inserts a value converted to string into this buffer

Inserts a string into this buffer at the position offset

Returns the number of characters in this buffer

Replaces the characters in this buffer from startIndex to endIndex with the specified string

Reveres the characters in the buffer

Sets a new character at the specified index in this buffer

Sets a new length in this buffer

Returns a substring starting at startIndex

Returns a substring from startIndex to endIndex

Page 47: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu47

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 charactersas the string argument. Initial capacity 16plus the length of the string argument.

Page 48: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

48

Liang,Introduction to Java Programming,revised by Dai-kaiyu

1 // Fig. 10.12: StringBufferConstructors.java2 // This program demonstrates the StringBuffer constructors.3 4 // Java extension packages5 import javax.swing.*;6 7 public class StringBufferConstructors {8 9 // test StringBuffer constructors10 public static void main( String args[] )11 {12 StringBuffer buffer1, buffer2, buffer3;13 14 buffer1 = new StringBuffer();15 buffer2 = new StringBuffer( 10 );16 buffer3 = new StringBuffer( "hello" );17 18 String output =19 "buffer1 = \"" + buffer1.toString() + "\"" +20 "\nbuffer2 = \"" + buffer2.toString() + "\"" +21 "\nbuffer3 = \"" + buffer3.toString() + "\"";22 23 JOptionPane.showMessageDialog( null, output,24 "Demonstrating StringBuffer Class Constructors",25 JOptionPane.INFORMATION_MESSAGE );26 27 System.exit( 0 );28 }29 30 } // end class StringBufferConstructors

Default constructor creates empty StringBuffer with

capacity of 16 characters

Second constructor creates empty StringBuffer with capacity of

specified (10) characters

Third constructor creates StringBuffer with String “hello” and

capacity of 16 characters

Method toString returns String representation of

StringBuffer

Page 49: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu49

StringBuffer Methods

Method length Return StringBuffer length

Method capacity Return StringBuffer capacity(the number can further contain)

Method setLength Increase or decrease StringBuffer length

Method toString Return the number of characters actually stored in the string

buffer.

Page 50: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu50

StringBuffer Methods

Manipulating StringBuffer characters Method charAt

Return StringBuffer character at specified index Method setCharAt

Set StringBuffer character at specified index Method getChars

Return character array from StringBuffer Method reverse

Reverse StringBuffer contents

Page 51: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

51

Liang,Introduction to Java Programming,revised by Dai-kaiyu

1 // StringBufferChars.java2 // The charAt, setCharAt, getChars, and reverse methods 3 // of class StringBuffer.4 5 // Java extension packages6 import javax.swing.*;7 8 public class StringBufferChars {9 10 // test StringBuffer character methods11 public static void main( String args[] )12 {13 StringBuffer buffer = new StringBuffer( "hello there" );14 15 String output = "buffer = " + buffer.toString() +16 "\nCharacter at 0: " + buffer.charAt( 0 ) +17 "\nCharacter at 4: " + buffer.charAt( 4 );18 19 char charArray[] = new char[ buffer.length() ];20 buffer.getChars( 0, buffer.length(), charArray, 0 );21 output += "\n\nThe characters are: ";22 23 for ( int count = 0; count < charArray.length; ++count )24 output += charArray[ count ];25 26 buffer.setCharAt( 0, 'H' );27 buffer.setCharAt( 6, 'T' );28 output += "\n\nbuf = " + buffer.toString();29 30 buffer.reverse();31 output += "\n\nbuf = " + buffer.toString();32

Return StringBuffer characters at indices 0

and 4, respectively

Return character array from StringBuffer

Replace characters at indices 0 and 6 with ‘H’

and ‘T,’ respectively

Reverse characters in StringBuffer

Page 52: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

52

Liang,Introduction to Java Programming,revised by Dai-kaiyu

33 JOptionPane.showMessageDialog( null, output,34 "Demonstrating StringBuffer Character Methods",35 JOptionPane.INFORMATION_MESSAGE );36 37 System.exit( 0 );38 }39 40 } // end class StringBufferChars

Page 53: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu53

Appending New Contentsinto a String Buffer

StringBuffer strBuf = new StringBuffer();strBuf.append("Welcome");strBuf.append(' ');strBuf.append("to");strBuf.append(' ');strBuf.append("Java");

Page 54: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

54

Liang,Introduction to Java Programming,revised by Dai-kaiyu

1 // StringBufferAppend.java2 // This program demonstrates the append3 // methods of the StringBuffer class.4 5 // Java extension packages6 import javax.swing.*;7 8 public class StringBufferAppend {9 10 // test StringBuffer append methods11 public static void main( String args[] )12 {13 Object o = "hello"; 14 String s = "good bye"; 15 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };16 boolean b = true;17 char c = 'Z';18 int i = 7;19 long l = 10000000;20 float f = 2.5f;21 double d = 33.333;22 StringBuffer buffer = new StringBuffer();23 24 buffer.append( o );25 buffer.append( " " );26

Append String “hello” to StringBuffer

Page 55: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

55

Liang,Introduction to Java Programming,revised by Dai-kaiyu

27 buffer.append( s );28 buffer.append( " " );29 buffer.append( charArray );30 buffer.append( " " );31 buffer.append( charArray, 0, 3 );32 buffer.append( " " );33 buffer.append( b );34 buffer.append( " " );35 buffer.append( c );36 buffer.append( " " );37 buffer.append( i );38 buffer.append( " " );39 buffer.append( l );40 buffer.append( " " );41 buffer.append( f );42 buffer.append( " " );43 buffer.append( d );44 45 JOptionPane.showMessageDialog( null,46 "buffer = " + buffer.toString(),47 "Demonstrating StringBuffer append Methods",48 JOptionPane.INFORMATION_MESSAGE );49 50 System.exit( 0 );51 }52 53 } // end StringBufferAppend

Append String “good bye”

Append “a b c d e f”

Append “a b c”

Append boolean, char, int, long, float and double

Page 56: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu56

StringBuffer Insertion and Deletion MethodsMethod insert

Allow data-type values to be inserted into StringBuffer

Methods delete and deleteCharAt Allow characters to be removed from StringBuffer

Page 57: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

57

Liang,Introduction to Java Programming,revised by Dai-kaiyu

1 // Fig. 10.16: StringBufferInsert.java2 // This program demonstrates the insert and delete3 // methods of class StringBuffer.4 5 // Java extension packages6 import javax.swing.*;7 8 public class StringBufferInsert {9 10 // test StringBuffer insert methods11 public static void main( String args[] )12 {13 Object o = "hello"; 14 String s = "good bye"; 15 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };16 boolean b = true;17 char c = 'K';18 int i = 7;19 long l = 10000000;20 float f = 2.5f;21 double d = 33.333;22 StringBuffer buffer = new StringBuffer();23

Page 58: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

58

Liang,Introduction to Java Programming,revised by Dai-kaiyu

24 buffer.insert( 0, o );25 buffer.insert( 0, " " );26 buffer.insert( 0, s );27 buffer.insert( 0, " " );28 buffer.insert( 0, charArray );29 buffer.insert( 0, " " );30 buffer.insert( 0, b );31 buffer.insert( 0, " " );32 buffer.insert( 0, c );33 buffer.insert( 0, " " );34 buffer.insert( 0, i );35 buffer.insert( 0, " " );36 buffer.insert( 0, l );37 buffer.insert( 0, " " );38 buffer.insert( 0, f );39 buffer.insert( 0, " " );40 buffer.insert( 0, d );41 42 String output = 43 "buffer after inserts:\n" + buffer.toString();44 45 buffer.deleteCharAt( 10 ); // delete 5 in 2.546 buffer.delete( 2, 6 ); // delete .333 in 33.33347 48 output += 49 "\n\nbuffer after deletes:\n" + buffer.toString();50 51 JOptionPane.showMessageDialog( null, output,52 "Demonstrating StringBufferer Inserts and Deletes",53 JOptionPane.INFORMATION_MESSAGE );54 55 System.exit( 0 );56 }57 58 } // end class StringBufferInsert

Use method insert to insert data types in beginning of

StringBuffer

Use method deleteCharAt to remove character from index 10 in

StringBuffer

Remove characters from indices 2 through 5 (inclusive)

Page 59: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu

59

Liang,Introduction to Java Programming,revised by Dai-kaiyu

Page 60: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu60

StringBuilder

Newly introduced in J2SE   5.0 Almost the same function with StringBuffer Do not deal with Synchronized , so has better

efficiency, compared with StringBuffer When frequently concatenate string,

StringBuilder and StringBuffer is more efficient than String

Demo TestAppendStringTime.java

Page 61: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu61

Example 7.3Checking Palindromes Ignoring Non-alphanumeric Characters

PalindromeIgnoreNonAlphanumeric PalindromeIgnoreNonAlphanumeric RunRun

Page 62: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu62

Class StringTokenizer

Tokenizer Partition String into individual substrings Use delimiter Java offers java.util.StringTokenizer

Page 63: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu63

The StringTokenizer Class

java.util.StringTokenizer

+StringTokenizer(s: String)

+StringTokenizer(s: String, delimiters: String)

+StringTokenizer(s: String, delimiters: String, returnDelimiters: boolean)

+countTokens(): int

+hasMoreTokens(): boolean

+nextToken(): String

+nextToken(delimiters: String): String

Constructs a string tokenizer for the string.

Constructs a string tokenizer for the string with the specified delimiters.

Constructs a string tokenizer for the string with the delimiters and returnDelims.

Returns the number of remaining tokens.

Returns true if there are more tokens left.

Returns the next token.

Returns the next token using new delimiters.

Page 64: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu64

Examples 1String s = "Java is cool.";StringTokenizer tokenizer = new StringTokenizer(s);

System.out.println("The total number of tokens is " + tokenizer.countTokens());

while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken());

The code displaysThe total number of tokens is 3Javaiscool.

Page 65: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu65

Examples 2String s = "Java is cool.";StringTokenizer tokenizer = new StringTokenizer(s, "ac");

System.out.println("The total number of tokens is " + tokenizer.countTokens());

while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken());

The code displaysThe total number of tokens is 4Jv isool.

Page 66: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu66

Examples 3String s = "Java is cool.";StringTokenizer tokenizer = new StringTokenizer(s, "ac", ture);

System.out.println("The total number of tokens is " + tokenizer.countTokens());

while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken());

The code displays The total number of tokens is 7Java iscool.

Delimiters counted as tokens

Page 67: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu67

No no-arg Constructor in StringTokenizer

The StringTokenizer class does not have a no-arg constructor.

Normally it is a good programming practice to provide a no-arg constructor for each class.

On rare occasions, however, a no-arg constructor does not make sense. StringTokenizer is such an example. A StringTokenizer object must be created for a string, which should be passed as an argument from a constructor.

Page 68: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu68

The Scanner Class

The delimiters are single characters in StringTokenizer. You can use the new JDK 1.5 java.util.Scanner class to specify a word as a delimiter.

JDK 1.5Feature

String s = "Welcome to Java! Java is fun! Java is cool!";Scanner scanner = new Scanner(s);scanner.useDelimiter("Java"); while (scanner.hasNext()) System.out.println(scanner.next());

Creates an instance of Scanner for the string.

Sets “Java” as a delimiter.

hasNext() returns true if there are still more tokens left.

The next() method returns a token as a string.

Welcome to! is fun! is cool!

Output

Page 69: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu69

Scanning Primitive Type Values

If a token is a primitive data type value, you can use the methods nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain it. For example, the following code adds all numbers in the string. Note that the delimiter is space by default.

JDK 1.5Feature

String s = "1 2 3 4";Scanner scanner = new Scanner(s); int sum = 0;while (scanner.hasNext()) sum += scanner.nextInt(); System.out.println("Sum is " + sum);

scanner.next().chatAt(0) get the char

Page 70: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu70

Console Input Using Scanner

Another important application of the Scanner class is to read input from the console.

JDK 1.5Feature

System.out.print("Please enter an int value: ");Scanner scanner = new Scanner(System.in);int i = scanner.nextInt();

NOTE: StringTokenizer can specify several single characters as delimiters. Scanner can use a single character or a word as the delimiter. So, if you need to scan a string with multiple single characters as delimiters, use StringTokenizer. If you need to use a word as the delimiter, use Scanner.

Page 71: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu71

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.

class TestMain { public static void main(String[] args) { ... }}

java TestMain arg0 arg1 arg2 ... argn

Page 72: Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live

Liang,Introduction to Java Programming,revised by Dai-kaiyu72

Example 7.4Using Command-Line Parameters

Objective: Write a program that will perform binary operations on integers. The program receives three parameters: an operator and two integers.

CalculatorCalculator

java Calculator 2 + 3

java Calculator 2 - 3

RunRun java Calculator 2 / 3

java Calculator 2 “*” 3