Lecture 3.1 - Java Strings and Characters
Lecture 3.1 - Java Strings and Characters
1
Character Type
A character data type represents a single
character.
2
Character Type
A character literal is enclosed in single
quotation marks.
3
Comparing and Testing
Characters
4
Character Class Methods
Java provides the following methods in the
Character class for testing characters
5
Example
6
Reading a Character from the
Console
To read a character from the console, use
the nextLine() method to read a string and
then invoke the charAt(0) method on the
string to return a character.
For example, the following code reads a
character from the keyboard:
7
8
Java Strings
Strings are used for storing text.
9
Example
10
String Length
A String in Java is actually an object,
which contain methods that can perform
certain operations on strings.
11
Example
12
More String Methods
toUpperCase() and toLowerCase()
13
Finding a String in a String
The indexOf() method returns the index
(the position) of the first occurrence of a
specified text in a string (including
whitespace):
Java counts positions from zero.
14
String Concatenation
The + operator can be used between strings
to add them together to make a new string.
This is called concatenation:
15
More String Methods
16
Reading a String from the
Console
To read a string from the console, invoke
the next() method on a Scanner object.
For example, the following code reads three
strings from the keyboard:
17
18
nextLine()
The next() method reads a string that ends
with a whitespace character.
You can use the nextLine() method to read
an entire line of text.
The nextLine() method reads a string that
ends with the Enter key pressed.
For example, the following statements read
a line of text.
19
20
Comparing Strings
21
Obtaining Substrings
22
Finding a Character or a
Substring in a String
23
Conversion between Strings and
Numbers
You can convert a numeric string into a
number.
To convert a string into an int value, use the
Integer.parseInt method, as follows:
24
To convert a string into a double value, use
the Double.parseDouble method, as
follows:
25
Special Characters
26
The sequence \" inserts a double quote in a
string:
27
Six other escape sequences are
valid in Java:
28
Adding Numbers and Strings
29
Adding Two Numbers
30
Adding Two Strings
31
Add a Number and a String
32