0% found this document useful (0 votes)
77 views50 pages

Topic5 - Strings

This document provides an overview of strings and character concepts in Java, including: - Character and string classes and operations like length(), charAt(), compare, uppercase/lowercase - Reading and writing strings from the console - Formatting strings with escape sequences and concatenation - Understanding Unicode encoding of characters - Analyzing string contents using methods of the Character class The learning outcomes are to use strings and characters to solve problems, explain their concepts and usage, and differentiate output formats.

Uploaded by

Abdul Majid
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)
77 views50 pages

Topic5 - Strings

This document provides an overview of strings and character concepts in Java, including: - Character and string classes and operations like length(), charAt(), compare, uppercase/lowercase - Reading and writing strings from the console - Formatting strings with escape sequences and concatenation - Understanding Unicode encoding of characters - Analyzing string contents using methods of the Character class The learning outcomes are to use strings and characters to solve problems, explain their concepts and usage, and differentiate output formats.

Uploaded by

Abdul Majid
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/ 50

COURSE - Problem Solving and

Programming Concepts (CSC3100)

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.

char letter = 'A'; //(ASCII)


char numChar = '4'; //(ASCII)
char letter = '\u0041'; //(Unicode)
char numChar = '\u0034'; //(Unicode)
NOTE: The increment and decrement operators can also be used
on char variables to get the next or preceding Unicode character.
For example, the following statements display character b.
char ch = 'a';
System.out.println(++ch);

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';

char c = 97; // Same as char c = (char)97;

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

toLowerCase(ch) Returns the lowercase of the specified character


ToUpperCase(ch) Returns the uppercase of the specified character

* Method is a group of statements that performs a specific task

13
Assume that an identifier ch is of type char.

if (Character.isLetter(ch)
System.out.println(ch + “ is a letter”);

This statement will check the type of ch if it 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

To display ASCII code for a character

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

The syntax to invoke an instance method is

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

The length of Welcome to Java is 15

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

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

For the statement

char ch = message.charAt(8); //returns character ‘t’ to ch

20
String Concatenation
Use the concat method
String s3 = s1.concat(s2);//s1 and s2 into s3
String s3 = s1 + s2; //same effect

String s1 = “We love “;


String s2 = “UPM”; String s3 = “We love “ + “UPM”;
String s3 = s1.concat(s2);

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

String s1 = new String("Welcome“);


String s2 = "welcome";

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.

String message = "Welcome to Java";

message.substring(0, 11); (beginIndex, endIndex)


- Returns a substring from the character at beginIndex to the character at
endIndex-1

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

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

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.

"Welcome to Java".indexOf('o', 5) returns 9.


- Returns the index of the first character in the string starting from the
specified index that matches the specified character.

"Welcome to Java".indexOf("come") returns 3.


- Returns the index of the first character of the substring in the string that
matches the specified string.

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

• To convert numeric string into a number


int intValue = Integer.parseInt(intString);

• To concert a string into a double value


double doubleValue = Double.parseDouble(doubleString);

• To convert a number into a string


String s = number + “”;

34
Case study
To convert a hexadecimal digit to decimal
value.

Hexadecimal digit: 0-9, A-F

Task: write a program to that prompts a user


to enter a hex digit and display the
corresponding decimal value
35
Case study
How to get the decimal?

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

System.out.printf(format, item1, item2,…, itemn);

where format is a string that may consists of substrings


and format specifiers.

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);

display count is 5 and amount is 45.560000


38
Specifying Width and Precision
Example Output
%5c Output the character and add four space before the character
%6b Output the Boolean value and add one space before false and
two spaces before the true value
%5d Output the integer item with width 5. if the number of digit in the
item is < 5, add spaces before the number. Otherwise the width
is automatically increased
%10.2f Output the floating-point item with width 10 including a decimal
point and two digits after the point.
%10.2e Output the floating-point item with width 10 including a decimal
point, two digits after the point and the exponent part
%12s Output the string with width 12 characters. If the string item has
fewer than 12 characters, add spaces before the string.
Otherwise the width is automatically increased

39
Example
System.out.printf(“%3d#%2s#%4.2f\n”, 1234, “Java”, 51.6653);

Displays

1234#Java#51.67

Display numbers with comma separators

System.out.printf(“%,8d %,10.1f\n”, 12345678, 12345678.263);

Output displayed

12,345,678 12,345,678.3

40
Example
Pad a number of leading zeros before a number

System.out.printf(“%08d %08.1f\n”, 1234, 5.63);

Output displayed

00001234 000005.6

By default, the output is right justified.

System.out.printf(“%8d%8s%8.1f\n”, 1234, “Java”, 5.63);

Output dispalyed

1234 Java 5.6

Four blank spaces Five blank spaces


41
Example

To make the output left justified.

System.out.printf(“%-8d%-8s%-8.1f\n”, 1234, “Java”, 5.63);

Output dispalyed

1234 Java 5.6

Four blank spaces Five blank spaces

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

50 + (int)(Math.random() * 50) return a random integer between 50 to 99

In general
a + Math.random() * b returns a random integer between a and a + b,
excluding a + b.

49
Terima Kasih | Thank You

You might also like