Topic5 - Strings
Topic5 - Strings
TOPIC 5 – Strings
• String and character classes
• String and character operations
• String formatting
• Existing library utilities
1
Learning Outcomes
• At the end of this chapter, student should
be able to:
– Construct program using character and string
(C3)
– Analyse and solve problem using string (C4,
CTPS)
– Explain the basic concepts and usage of
string (C2)
– Differentiate type of format output (C4)
2
Character Data Type and
Operations
• Character data type represents a single character.
• to declare a single character we used char
• A character literal is enclosed in single quotation marks,
• Example
char letter = ‘A’;
char singleDigit = ‘4’;
3
Character Data Type
Four hexadecimal digits.
4
Unicode Format
• Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in
the world’s diverse languages.
• Unicode takes two bytes, preceded by \u, expressed in
four hexadecimal numbers that run from '\u0000' to '\
uFFFF'. So, Unicode can represent 65535 + 1
characters.
Unicode \u03b1 \u03b2 \u03b3 for three Greek
letters
5
Appendix B: ASCII Character
Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
6
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
7
Escape Sequences for Special
Characters
• Suppose you want to print
He said “Java is fun”
• Can you write:
System.out.println(“He said “Java is fun” ”);
error
• You should write:
System.out.println(“He said \“Java is fun\” ”);
8
Escape Sequences for Special
Characters
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022
9
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
10
Comparing and Testing
Characters
• Two characters can be compared using relational
operators
• It is done by comparing the Unicode of the two
characters
eg.
‘a’ < ‘b’ is true
‘a’ < ‘A’ is false
‘1’ < ‘8’ is true
11
Comparing and Testing
Characters
• Often we need to test whether a character is a number, a letter, an
uppercase letter or a lowercase letter
eg. Let variable ch as a char data tye
if (ch >= ‘A’ && ch <= ‘Z’)
System.out.println(ch + “ is an uppercase letter”);
else if (ch >= ‘a’ && ch <= ‘z’)
System.out.println(ch + “ is a lowercase letter”);
else if (ch >= ‘0’ && ch <= ‘9’)
System.out.println(ch + “ is a numeric character”);
12
The Character Class
Method Dsecription
isDigit(ch) Returns true if the specified character is a digit
isLetter(ch) Returns true if the specified character is a letter
isLetterOrDigit(ch) Returns true if the specified character is a letter or digit
isLowerCase(ch) Returns true if the specified character is a lowercase
letter
isUpperCase(ch) Returns true if the specified character is an uppercase
letter
13
Assume that an identifier ch is of type char.
if (Character.isLetter(ch)
System.out.println(ch + “ is a letter”);
14
Reading a character from the Console
• We can use nextLine() or next() method to read a
string and then invoke the charAt(0) method.
• For example
Scanner input = new Scanner(System.in);
System.out.print(“Enter a character: “);
String st = input.nextLine();
Char ch = st.charAt(0);
System.out.println(“The character entered is “ + ch);
15
Case study
16
The String Class
• To represent a string of characters, use the data type String
• 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 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
17
Simple methods for String
objects
Method Description
length() Returns the number of characters in this string
charAt(index) Returns the characters at the specified index from this string
concat(s1) Returns a new string that concatenates this string with string s1
toUpperCase() Returns a new string with all letters in uppercase
toLowerCase() Returns a new string with all letters in lowercase
trim() Returns a new string with whitespace characters trimmed on
both sides
referenceVariable.methodName(argument)
18
Finding String Length
Finding a string length using the length()
method:
String message = "Welcome to Java";
System.out.println(“The length of “ + message + “ is
” + message.length());
displays
19
Getting Characters from a
String
• The method charAt(index) is used. The index is between 0 to the
string length-1.
• For example, message.charAt(index)
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
20
String Concatenation
Use the concat method
String s3 = s1.concat(s2);//s1 and s2 into s3
String s3 = s1 + s2; //same effect
System.out.println(s3);
Displays
We love UPM
21
• Operator + can also concatenate a non-
string with a string. (at least one operand
must be a string)
• Can also use augmented += operator
• Example
int i = 1;
int j = 2;
System.out.println("i + j is " + i + j);
22
Reading a String from the Console
• Use next() method on a Scanner object. This
method read a string that ends with a whitespace
character
• For example:
Scanner input = new Scanner(System.in);
System.out.print(“Enter three words separated by spaces: “);
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println(“s1 is “ + s1);
System.out.println(“s2 is “ + s2);
System.out.println(“s3 is “ + s3);
23
Reading a String from the Console
• Use nextLine() method to read the entire line of
text. This method reads a string that ends with the
Enter key pressed. (line-based input)
• For example
Scanner input = new Scanner(System.in);
System.out.print(“Enter a message: “);
String msg = input.nextLine();
System.out.println(“The message entered is “ + msg);
24
caution
• To avoid input errors, do not use a line-
based input after a token-based input.
25
Reading a Character from the Console
• We can use nextLine() method to read a string
and then invoke the charAt(0) method.
• For example
Scanner input = new Scanner(System.in);
System.out.print(“Enter a character: “);
String st = input.nextLine();
Char ch = st.charAt(0);
System.out.println(“The character entered is “ + ch);
26
Comparing Strings
Method Description
equals(s1) Returns true if this string is equal to s1
equalsIgnoreCase(s1) Returns true if this string is equal to s1; it is case insensitive
compareTo(s1) Returns an integer greater than 0, equal to 0, or less than 0 to
indicate whether the string is greater than, equal to, or less than s1
startWith(prefix) Returns true if this string starts with the specified prefix
endWith(suffix) Returns true if this string ends with the specified suffix
contains(s1) Returns true if s1 is a substring in this string
27
String Comparisons
• equals
if (s1.equals(s2)){
// s1 and s2 have the same contents
}
28
String Comparisons, cont.
• compareTo(Object object)
A = 65
String s1 = new String("Welcome“); a = 97
String s2 = "welcome"; …
W = 87
if (s1.compareTo(s2) > 0) { w = 119
// s1 is greater than s2
}
else if (s1.compareTo(s2) == 0) {
// s1 and s2 have the same contents
}
else
// s1 is less than s2
29
Obtaining Substrings
• You can obtain a substring from a string using the
substring method in the String class.
message.substring(11); beginIndex
- Returns a substring from the character at beginIndex to the last character
(end of string)
30
Extracting Substrings
String message = "Welcome to Java";
String s1 = message.substring(0, 11);
String s2 = message.substring(11);
String s3 = message.substring(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
s3 is "Welcome to HTML";
31
Finding a Character or a
Substring in a String
"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('x') returns -1.
- Return the index of the first character in the string that matches the
specified character.
32
"Welcome to Java".indexOf("Java", 5) returns 11.
"Welcome to Java".indexOf("java", 5) returns -1.
• Returns the index of the first character of the substring in the string
starting from the specified index that matches the specified string.
"Welcome to Java".lastIndexOf('a')
returns 14.
33
Conversion between Strings and Numbers
34
Case study
To convert a hexadecimal digit to decimal
value.
A = 10 0 + 10 65 – 65 + 10 ‘A’ – ‘A’ + 10
B = 11 1 + 10 66 – 65 + 10 ‘B’ – ‘A’ + 10
C = 12 2 + 10 67 – 65 + 10 ‘C’ – ‘A’ + 10
D = 13 3 + 10 68 – 65 + 10 ‘D’ – ‘A’ + 10
E = 14 4 + 10 69 – 65 + 10 ‘E’ – ‘A’ + 10
F = 15 5 + 10 70 – 65 + 10 ‘F’ – ‘A’ + 10
ASCII code: ‘A’ is 65, ‘B’ is 66, ‘C’ is 67, ‘D’ is 68 ch – ‘A’ + 10
‘E’ is 69, ‘F’ is 70
36
Formatting Console Output
• You have been introduced with printf method to display
formatted output
• The general syntax
37
Frequently-Used Specifiers
Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%s a string "Java is cool"
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
39
Example
System.out.printf(“%3d#%2s#%4.2f\n”, 1234, “Java”, 51.6653);
Displays
1234#Java#51.67
Output displayed
12,345,678 12,345,678.3
40
Example
Pad a number of leading zeros before a number
Output displayed
00001234 000005.6
Output dispalyed
Output dispalyed
42
Common Mathematical Functions
• Java provides many useful methods in the Math
class for performing common mathematical functions.
• Methods in Math class
– Class constants:
• PI
– Class methods:
• Trigonometric Methods
• Exponent Methods
• Rounding Methods
• min, max, abs, and random Methods
43
Trigonometric Methods
• sin(radians) Examples:
• cos(radians)
Math.sin(0) returns 0.0
• tan(radians)
Math.sin(Math.PI / 6)
• acos(a) returns 0.5
• asin(a) Math.sin(Math.PI / 2)
returns 1.0
• atan(a) Math.cos(0) returns 1.0
• toRadian(degree) Math.cos(Math.PI / 6)
returns 0.866
• toDegree(radian)
Math.cos(Math.PI / 2)
returns 0
44
Exponent Methods
Examples:
• exp(x)
Returns e raised to the power of x. Math.exp(1) returns 2.71
• log(x) Math.log(2.71) returns 1.0
Returns the natural logarithm of x. Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
• log10(x)
Math.pow(3.5, 2.5) returns
Returns the 10-based logarithm of x. 22.91765
• pow(a,b) Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns
Returns a raised to the power of b.
3.24
• sqrt(x)
Returns the square root of x.
45
Rounding Methods
• ceil(x)
x rounded up to its nearest integer. This integer is returned as
a double value.
• floor(x)
x is rounded down to its nearest integer. This integer is
returned as a double value.
• rint(double x)
x is rounded to its nearest integer. If x is equally close to two
integers, the even one is returned as a double.
• round(x)
Return (int)Math.floor(x+0.5) if x is float
• round(x)
Return (long)Math.floor(x+0.5) if x is double
46
Rounding Methods Examples
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3
47
min, max, abs, random
• max(a, b)and min(a, Examples:
b)
Returns the maximum or Math.max(2, 3) returns 3
minimum of two parameters. Math.max(2.5, 3) returns 3.0
• abs(a) Math.min(2.5, 3.6) returns 2.5
Returns the absolute value of Math.abs(-2) returns 2
the parameter. Math.abs(-2.1) returns 2.1
• random()
Returns a random double
value
in the range [0.0, 1.0).
48
Random method
•random()
Returns
a random double value in the range [0.0, 1.0).
(int) (Math.random() * 10) return a random integer between 0 and 9
In general
a + Math.random() * b returns a random integer between a and a + b,
excluding a + b.
49
Terima Kasih | Thank You