Inner Classes And
Strings
Objectives:
Learn about Inner Classes
Learn about literal strings
Learn about String constructors and
commonly used methods
Understand immutability of strings
Learn to convert strings into numbers and
numbers into strings
Learn several useful methods of the
Character class
9-2
The Inner class
It is possible to define a class within another class;
such classes are known as nested classes.
The scope of a nested class is bounded by the
scope of its enclosing class.
Thus, if class B is defined within class A, then B is
known to A, but not outside of A.
A nested class has access to the members,
including private members, of the class in which it
is nested.
However, the enclosing class does not have
access to the members of the nested class.
9-3
The Inner class (Cont’d)
There are two types of nested classes: static and
non-static.
A static nested class is one which has the static
modifier applied. Because it is static, it must
access the members of its enclosing class
through an object.
That is, it cannot refer to members of its enclosing
class directly.
Because of this restriction, static nested classes
are seldom used.
9-4
The Inner class (Cont’d)
The most important type of nested class is the
inner class.
An inner class is a non-static nested class.
It has access to all of the variables and methods of
its outer class and may refer to them directly in the
same way that other non-static members of the
outer class do.
Thus, an inner class is fully within the scope of its
enclosing class.
9-5
The Inner class Example
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
Output:
display: outer_x = 100
9-6
The Inner class Example
// This program will not compile.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
System.out.println("display: outer_x = " +
outer_x);
}
}
void showy() {
System.out.println(y); // error, y not known
here!
}
}
class InnerClassDemo {
public static void main(String
args[]) {
Outer outer = new Outer();
outer.test();
}
}
9-7
The String class
An object of the String class represents a string of
characters.
The String class belongs to the java.lang package,
which is built into Java.
Like other classes, String has constructors and
methods.
Unlike other classes, String has two operators, +
and += (used for concatenation).
9-8
Literal Strings
Literal strings are anonymous constant objects of
the String class that are defined as text in double
quotes.
The string text may include “escape” characters for
example:
\\ stands for \
\n stands for the newline character
"Biology”, "C:\\jdk1.4\\docs”, "Hello\n"
9-9
Literal Strings (cont’d)
don’t have to be constructed: they are “just
there.”
can be assigned to String variables.
can be passed to methods and constructors as
arguments.
have methods you can call:
String fileName = "fish.dat";
button = new JButton("Next slide");
if (”Start".equals(cmd)) ...
9-10
Immutability
Once created, a string cannot be changed: none of
its methods changes the string.
Such types of objects are called immutable.
Immutable objects are convenient because two
references can point to the same object safely.
There is no danger of changing an object through
one reference without the others being aware of the
change.
9-11
Immutability (cont’d)
Advantage: more efficient, no need to copy.
String s1 = "Sun";
String s2 = s1;
s1
String s1 = "Sun";
String s2 = new String(s1);
s1
"Sun"
s2
"Sun"
"Sun"
s2
OK
Less efficient
and wasteful
9-12
Immutability (cont’d)
Disadvantage: less efficient — you need to create a
new string and throw away the old one for every
small change.
String s = "sun";
char ch = Character.toUpper(s.charAt (0));
s = ch + s.substring (1);
s
"sun"
'S'
+ "un"
9-13
Empty Strings
An empty string has no characters; its length is 0.
String s1 = "";
String s2 = new String();
Empty strings
Not to be confused with an uninitialized string:
private String errorMsg;
errorMsg is null
9-14
Constructors
String’s no-args and copy constructors are
not used much.
String s1 = new String ();
String s1 = "";
String s2 = new String (s1);
String s2 = s1;
Other constructors convert arrays into strings.
9-15
Methods — length, charAt
int length ();
Returns the number of
characters in the string
char charAt (k);
Returns the k-th char
Character positions in strings
are numbered starting from 0
Returns:
”Flower".length();
6
”Wind".charAt (2);
’n'
9-16
Methods — substring
String s2 = s.substring (i, k);
returns the substring of chars in
positions from i to k-1
strawberry
i k
String s2 = s.substring (i);
returns the substring from the i-th char to the
end
Returns:
”raw"
”strawberry".substring (2,5);
"happy"
"unhappy".substring (2);
"" (empty string)
"emptiness".substring (9);
9-17
Methods — Concatenation
String result = s1 + s2;
concatenates s1 and s2
String result = s1.concat (s2);
the same as s1 + s2
result += s3;
concatenates s3 to result
result += num;
converts num to String and concatenates
it to result
9-18
Methods — Find (indexOf)
0
8
11
15
String date ="July 5, 2012 1:28:19 PM";
date.indexOf ('J');
date.indexOf ('2');
date.indexOf ("2012");
date.indexOf ('2', 9);
Returns:
0
8
8
(starts searching
11
at position 9)
date.indexOf ("2020");
-1
date.lastIndexOf ('2');
15
(not found)
9-19
Methods — Comparisons
boolean b = s1.equals(s2);
returns true if the string s1 is equal to s2
boolean b = s1.equalsIgnoreCase(s2);
returns true if the string s1 matches s2, caseblind
int diff = s1.compareTo(s2);
returns the “difference” s1 - s2
int diff = s1.compareToIgnoreCase(s2);
returns the “difference” s1 - s2, case-blind
9-20
Methods — Replacements
String s2 = s1.trim ();
returns a new string formed from s1 by
removing white space at both ends
String s2 = s1.replace(oldCh, newCh);
returns a new string formed from s1 by
replacing all occurrences of oldCh with newCh
String s2 = s1.toUpperCase();
String s2 = s1.toLowerCase();
returns a new string formed from s1 by
converting its characters to upper (lower) case
9-21
Replacements (cont’d)
Example: how to convert s1 to upper case
s1 = s1.toUpperCase();
A common bug:
s1.toUpperCase();
s1 remains
unchanged
9-22
Methods — toString
It is customary to provide a toString
method for your class.
toString converts an object into a String
(for printing it out, for debugging, etc.).
System.out.print (obj);
is the same as
System.out.print (obj.toString());
9-23
Numbers to Strings and
Strings to Numbers
Integer and Double are “wrapper” classes
from java.lang that represent numbers as
objects.
Integer and Double provide useful static
methods for conversions:
String s1 = Integer.toString (i);
String s2 = Double.toString (d);
int i;
double d;
int n = Integer.parseInt (s1);
double x = Double.parseDouble (s2);
9-24
Numbers to Strings
Three ways to convert a number into a string:
1.
String s = "" + num;
2.
String s = Integer.toString (i);
String s = Double.toString (d);
int i;
double d;
3.
String s = String.valueOf (num);
9-25
Numbers to Strings
(cont’d)
The DecimalFormat class can be used
for more controlled conversions of
numbers into strings:
import java.text.DecimalFormat;
...
DecimalFormat money =
new DecimalFormat("0.00");
...
double amt = …;
...
String s = money.format (amt);
56.7899
"56.79"
9-26
Strings to Numbers
int n = Integer.parseInt(s);
double x = Double.parseDouble(s);
These methods throw a
NumberFormatException if s does not
represent a valid number.
Older versions of SDK (before 1.2) did not
have Double.parseDouble; you had to use
double x = Double.valueOf(s).doubleValue();
9-27
Character Methods
java.lang.Character is a class that represents
characters as objects.
Character has several useful static methods that
determine the type of a character.
Character also has methods that convert a letter to
the upper or lower case.
9-28
Character Methods (cont’d)
if (Character.isDigit (ch)) ...
.isLetter...
.isLetterOrDigit...
.isUpperCase...
.isLowerCase...
.isWhitespace...
Whitespace is
space, tab,
newline, etc.
return true if ch belongs to the
corresponding category
9-29
Character methods (cont’d)
char ch2 = Character.toUpperCase (ch1);
.toLowerCase (ch1);
if ch1 is a letter, returns its upper (lower)
case; otherwise returns ch1
int d = Character.digit (ch, radix);
returns the int value of the digit ch in the
given int radix
char ch = Character.forDigit (d, radix);
returns a char that represents int d in a
given int radix
9-30
StringTokenizer
java.util.StringTokenizer is used to extract
“tokens” from a string.
Tokens are separated by delimiters (e.g.,
whitespace).
A tokenizer object is constructed with a given
string as an argument.
The second optional argument is a string that
lists all delimiters (default is whitespace).
9-31
StringTokenizer (cont’d)
import java.util.StringTokenizer;
Delimiters are
...
whitespace
String str = input.readLine();
StringTokenizer q =
new StringTokenizer (str);
All delimiters
// or:
// new StringTokenizer (str, ";+ \t, ");
int n = q.countTokens ();
while ( q.hasMoreTokens() )
{
String word = q.nextToken();
...
The number of
found tokens
9-32
© Copyright 2026 Paperzz