IT 102 - PROGRAMMING 2
Instructor: Jayson Bonggo
Character and String
Class Methods
OBJECTIVES
Identify string data problems
Use Character class methods
Declare and compare Strings
class
Use a variety of Character and
String methods
STRINGS IN JAVA
You’ve been using Strings in methods like
print(), println(), and printf() since the start of
the course. However, working with Characters
and Strings can be tricky for beginners and
requires a deeper understanding of how they
function in Java.
STRINGS IN JAVA
In the TryToCompareStrings
application (Figure 7-1), a String
variable aName is declared and
assigned the value "Carmen".
The user is asked to input a name, and
the program compares the input with
aName using the == operator.
STRINGS IN JAVA
Even if the user enters "Carmen", the
program says the names are not equal
(Figure 7-2). This seems incorrect.
STRINGS IN JAVA
A String variable is not a simple data
type but a reference—it holds a
memory address, not the actual
value.
When you use == to compare two
Strings, you’re comparing their
memory addresses, not their
actual values.
CHARATERS AND STRINGS IN JAVA
Programmers usually want to compare the values
of Strings, not their memory addresses.
Java provides tools to make working with text
easier, including classes like Character and
String.
CHARATERS AND STRINGS IN JAVA
Java Classes for Text Data
Character Class:
Holds a single character (e.g., 'A', '8', '$').
Provides methods to manipulate and inspect
single-character data.
CHARATERS AND STRINGS IN JAVA
Java Classes for Text Data
String Class:
Used for fixed (unchanging) text data made
up of one or more characters.
Offers many methods to simplify working with
Strings.
USING CHARACTER CLASS METHODS
The char Data Type:
Used to store a single character, such as a
letter, digit, or punctuation mark.
char literals are written inside single quotation
marks (e.g., 'A', '1', '$').
Since char is a primitive data type, it holds
actual values (not memory addresses).
You can compare char values using relational
operators like == and >.
USING CHARACTER CLASS METHODS
How Character Comparisons Work:
Comparisons are based on the Unicode value of
each character.
These comparisons work as you’d expect—
alphabetically.
Example: If yourInitial is 'A' and myInitial is 'B',
then yourInitial < myInitial is true because 'A'
comes before 'B' in Unicode.
USING CHARACTER CLASS METHODS
Java also provides a Character class for working
with characters.
This class includes useful methods for testing and
manipulating character values.
The Character class is part of the java.lang
package, which is automatically imported into
every Java program.
USING CHARACTER CLASS METHODS
Character Class Methods
isLetter(char ch)
isDigit(char ch)
isWhitespace(char ch)
toUpperCase(char ch)
toLowerCase(char ch)
isUpperCase(char ch)
isLowerCase(char ch)
toString(char ch)
isLetterOrDigit(char ch)
compare(char x, char y)
USING CHARACTER CLASS METHODS
isLetter(char ch)
Checks if the given character is a letter
(uppercase or lowercase).
Syntax:
Character.isLetter(char ch);
USING CHARACTER CLASS METHODS
isDigit(char ch)
Checks if the given character is a digit
(0-9).
Syntax:
Character.isDigit(char ch);
USING CHARACTER CLASS METHODS
isWhitespace(char ch)
Checks if the given character is a
whitespace (space, tab, newline, etc.).
Syntax:
Character.isWhitespace(char ch);
USING CHARACTER CLASS METHODS
toUpperCase(char ch)
Converts the given character to its
uppercase equivalent.
Syntax:
Character.toUpperCase(char ch);
USING CHARACTER CLASS METHODS
toLowerCase(char ch)
Converts the given character to its
lowercase equivalent.
Syntax:
Character.toLowerCase(char ch);
USING CHARACTER CLASS METHODS
isUpperCase(char ch)
Checks if the given character is an
uppercase letter.
Syntax:
Character.isUpperCase(char ch);
USING CHARACTER CLASS METHODS
isLowerCase(char ch)
Checks if the given character is a
lowercase letter.
Syntax:
Character.isLowerCase(char ch);
USING CHARACTER CLASS METHODS
toString(char ch)
Converts the given character to a
String.
Syntax:
Character.toString(char ch);
USING CHARACTER CLASS METHODS
isLetterOrDigit(char ch)
Checks if the given character is a letter
or a digit.
Syntax:
Character.isLetterOrDigit(char ch);
USING CHARACTER CLASS METHODS
compare(char x, char y)
Compares two characters numerically
based on their Unicode values.
Syntax:
Character.compare(char x, char y);
USING CHARACTER CLASS METHODS
compare(char x, char y)
Compares two characters numerically based on their Unicode values.
Syntax:
Character.compare(char x, char y);
USING CHARACTER CLASS METHODS
Write a Java program that:
1. Asks the user to enter a single
character.
2. Checks if the character is a letter,
digit, or symbol.
3. If the character is a letter, converts it to
uppercase and lowercase.
4. Displays the results to the user.
USING CHARACTER CLASS METHODS
JAVA STRING
Strings are one of the most common
dataType in Java.
A String variable is a reference—it stores a
memory address, not the actual value.
JAVA STRING
Difference Between Primitive Types and Strings
Primitive Types (e.g., int):
When you declare int x = 10;, the memory address of x
holds the value 10.
If you update x to 45, the new value replaces the old
one at the same memory address.
Strings:
When you declare String aGreeting = "Hello";,
aGreeting holds the memory address of the String "Hello",
not the actual characters.
This distinction is fine but important for understanding how
Strings work in Java.
JAVA STRING
How Strings Work in Memory
Memory Addresses
When you declare a String like String
aGreeting = "Hello";, the variable
aGreeting holds a memory address
(e.g., 26040) where the actual characters
"Hello" are stored.
You cannot choose memory
addresses; they are assigned by the
operating system.
JAVA STRING
How Strings Work in Memory
Memory Addresses
Strings are immutable—they are never
changed. Instead, new Strings are
created, and references are updated to
point to the new memory addresses.
JAVA STRING
Comparing Strings
Using == Operator:
When you compare Strings with ==, you are comparing their
memory addresses, not their actual values.
Using < or > Operators:
Comparing Strings with < or > will cause a compilation error. These
operators cannot be used with Strings.
JAVA STRING
Escape Sequences in Strings
Common Escape Sequences:
JAVA STRING
Concatenating Strings
Use the + operator to combine (concatenate) Strings.
JAVA STRING
Difference Between Strings and Characters
String Literals:
Marked by double quotes ("), e.g., "a".
Can be one or more characters long.
Character Literals:
Marked by single quotes ('), e.g., 'a'.
Always exactly one character long.
JAVA STRING
Empty and Null Strings
Empty String:
Created using double quotes with no characters
inside, e.g., String word1 = "";.
Refers to a memory address where no characters are
stored.
Can be used with String methods like .equals().
JAVA STRING
Empty and Null Strings
Null Strings:
Created by assigning null to a String, e.g., String
word2 = null;.
Alternatively, an unassigned String (e.g., String
word3;) is also null by default.
A null String does not reference any memory address.
Cannot be used with String methods like .equals()
—it will cause an error.
JAVA STRING
Empty and Null Strings
Null Strings:
Some programmers prefer to explicitly set Strings to
null (e.g., String word2 = null;) to make their code
clearer.
Others find it redundant since unassigned Strings are
null by default.
JAVA STRING
JAVA STRING METHODS
length() isBlank()
indexOf() isEmpty()
charAt() strip()
startsWith() toLowerCase()
endsWith() toUpperCase()
replace() trim()
contains()
toString()
substring()
indexOf(String, int)
JAVA STRING
length()
Returns the number of characters in a String.
JAVA STRING
indexOf()
Finds the position of a character or substring in a String.
JAVA STRING
charAt()
Returns the character at a specific position.
JAVA STRING
substring()
Extracts part of a String.
The substring() method takes two integer arguments—a start position and
an end position—that are both based on the fact that a String’s first
position is position zero.
The length of the extracted substring is the difference between the
second integer and the first integer; if you call the method without a
second integer argument, the substring extends to the end of the original string.
JAVA STRING
startsWith()
Checks if a String starts with a specific substring.
JAVA STRING
endsWith()
Checks if a String ends with a specific substring.
JAVA STRING
replace()
Replaces all occurrences of a character or String/substring.
JAVA STRING
contains()
Checks if a String contains a specific substring.
JAVA STRING
toString()
Converts current dataType to a String (implicitly used in print()
and println()).
JAVA STRING
indexOf(String, int)
Finds the position of a substring starting from a specific index.
JAVA STRING
isBlank()
Checks if a String is empty or contains only whitespace.
JAVA STRING
isEmpty()
Checks if a String has no characters.
JAVA STRING
toLowerCase()
Converts the String to lowercase.
JAVA STRING
toUpperCase()
Converts the String to uppercase.
JAVA STRING
strip()
Removes leading and trailing whitespace.
JAVA STRING
trim()
Removes leading and trailing whitespace (similar to strip() but
available in older Java versions).
CONVERTING STRING TO NUMBERS
Why Convert Strings to Numbers?
If a String contains only numbers (e.g., "649"),
you can convert it to a numeric type (like int
or double) to perform arithmetic operations.
Example: When a user enters a value (e.g.,
salary) in an input dialog box, the input is
always a String. To use it in calculations, you
must convert it to a number.
CONVERTING STRING TO NUMBERS
How to Convert Strings to Numbers
Using Integer
It provides the parseInt() method,
which takes a String and returns its
integer value.
parseInt() is a static method, so
you call it using the class name
(Integer.parseInt()).
CONVERTING STRING TO NUMBERS
How to Convert Strings to Numbers
Using Double
It provides the parseDouble() method, which takes a
String and returns its double values.
CONVERTING STRING TO NUMBERS
How to Convert Strings to Numbers
Other conversion methods:
ParseFloat
ParseLong
JAVA STRING METHODS
Create a Java program that should perform the following:
JAVA STRING METHODS
JAVA STRING AND CHARACTER CLASS METHODS
REVIEW
Strings are one of the most commonly used objects in
Java.
A String variable is a reference—it holds a memory
address where the actual characters are stored, not the
value itself.
Strings are immutable—once created, they cannot be
changed. Instead, new Strings are created when
modifications are made.
JAVA STRING AND CHARACTER CLASS METHODS
REVIEW
Common String Methods
length(): Returns the number of characters in a String.
indexOf(): Finds the position of a character or substring
in a String. Returns -1 if not found.
charAt(): Returns the character at a specific position in a
String.
startsWith() and endsWith(): Check if a String starts or
ends with a specific substring.
JAVA STRING AND CHARACTER CLASS METHODS
REVIEW
Common String Methods
replace(): Replaces all occurrences of a character or
substring in a String.
contains(): Checks if a String contains a specific substring.
substring(): Extracts part of a String based on start and end
positions.
toUpperCase() and toLowerCase(): Convert a String to
uppercase or lowercase.
JAVA STRING AND CHARACTER CLASS METHODS
REVIEW
Common String Methods
trim(): Removes leading and trailing whitespace from a
String.
isBlank() (Java 11+): Checks if a String is empty or contains
only whitespace.
isEmpty(): Checks if a String has no characters.
strip() (Java 11+): Removes leading and trailing whitespace
(similar to trim() but more Unicode-aware).
JAVA STRING AND CHARACTER CLASS METHODS
REVIEW
Empty String: Created using "". It references a memory
address but contains no characters.
Null String: Created by assigning null or leaving a String
uninitialized. It does not reference any memory address.
Key Difference:
Empty Strings can be used with String methods like
isEmpty() or equals().
Null Strings cannot be used with String methods—it will
cause a NullPointerException.
JAVA STRING AND CHARACTER CLASS METHODS
REVIEW
Converting Strings to Numbers
Use classes like Integer, Double, Float, and Long to convert
Strings to numbers.
Integer.parseInt(): Converts a String to an int.
Double.parseDouble(): Converts a String to a double.
Float.parseFloat(): Converts a String to a float.
Long.parseLong(): Converts a String to a long.
JAVA STRING AND CHARACTER CLASS METHODS
REVIEW
Using == to compare Strings (compares memory addresses,
not values).
Forgetting to handle null Strings, leading to runtime errors.
Misusing methods like charAt() with invalid positions (causing
StringIndexOutOfBoundsException).
JAVA STRING AND CHARACTER CLASS METHODS
REVIEW
Use .equals() to compare String values, not ==.
Always initialize Strings to avoid null issues.
Use methods like isBlank() and isEmpty() to handle empty or
whitespace-only Strings.
Modularize code by breaking tasks into separate methods.
JAVA METHODS
REFERENCES:
https://www.w3schools.com/java/java_ref_string.asp
https://www.programiz.com/java-programming/library/string
https://dev.to/pankaj_singhr/10-most-useful-string-methods-in-java-4lag
https://www.simplilearn.com/tutorials/java-tutorial/java-strings
https://www.tutorialspoint.com/java/java_characters.htm
https://www.scaler.com/topics/character-class-in-java/
IT 102 - PROGRAMMING 2
END OF SLIDE