Core Java Programming 1
Core Java Programming 1
12/29/08 1
List of Contents
Arrays in Java
String
StringBuffer
StringTokenizer
12/29/08 2
Arrays in Java
Arrays are fixed-length structures for storing
multiple values of the same type. An array
implicitly extends java.lang.Object so an array
is an instance of Object.
But arrays are directly supported language
features. This means that their performance is
on par with primitives and that they have a
unique syntax that is different than objects.
12/29/08 3
Structure of Java Arrays
12/29/08 4
Java Array Declaration
An array variable is declared the same way that any
Java variable is declared. It has a type and a valid
Java identifier.
The type is the type of the elements contained in the
array.
The [ ] notation is used to denote that the variable is
an array.
Some examples:
int[] counts;
String[] names;
int[][] matrix; //this is an array of arrays
12/29/08 5
Java Array Initialization
Once an array variable has been declared, memory
can be allocated to it. This is done with the new
operator, which allocates memory for objects.
(Remember arrays are implicit objects.)
The new operator is followed by the type, and finally,
the number of elements to allocate. The number of
elements to allocate is placed within the [ ] operator.
Some examples:
counts = new int[5];
names = new String[100];
matrix = new int[5][];
12/29/08 6
… Continued
12/29/08 7
Java Array Usage
To reference an element within an array,
use the [ ] operator.
This operator takes an int operand and
returns the element at that index.
Remember that array indices start with
zero, so the first element is referenced
with index 0.
int month = months[3];
//get the 4th month (April)
12/29/08 8
… Continued
12/29/08 9
… Continued
A Sample program is as follows:
class ArrayTest
{
public static void main(String[] args)
{
String months[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
12/29/08 10
… Continued
C:\>javac ArrayTest.java
C:\>java ArrayTest
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
C:\>
12/29/08 11
… Continued
Using Java 5.0, the enhanced for loop makes this even easier:
class ArrayTest
{
public static void main(String[] args)
{
String months[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
12/29/08 12
… Continued
C:\>javac ArrayTest.java
C:\>java ArrayTest
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
C:\>
12/29/08 13
… Continued
Arrays are a great way to store several to
many values that are of the same type and
that are logically related to one another: lists of
invoices, lists of names, lists of Web page hits,
etc.
But, being fixed-length, if the number of values
you are storing is unknown or changes, there
are better data structures available in the Java
Collections API.
These include ArrayList and HashSet,
amongst others.
12/29/08 14
What is a String?
java.lang.String
The String class represents character
strings. All string literals in Java
programs, such as "abc", are
implemented as instances of this class.
Strings are constant; their values cannot
be changed after they are created.
12/29/08 15
… Continued
12/29/08 16
What is StringBuffer?
java.lang.StringBuffer
A string buffer implements a mutable
sequence of characters.
A string buffer is like a String, but can be
modified.
At any point in time it contains some particular
sequence of characters, but the length and
content of the sequence can be changed
through certain method calls.
12/29/08 17
… Continued
The principal operations on a StringBuffer are
the append and insert methods, which are
overloaded so as to accept data of any type.
Each effectively converts a given datum to a
string and then appends or inserts the
characters of that string to the string buffer.
The append method always adds these
characters at the end of the buffer; the insert
method adds the characters at a specified
point.
12/29/08 18
… Continued
12/29/08 19
… Continued
The Java language provides special support
for the string concatenation operator (+), and
for conversion of other objects to strings.
String concatenation is implemented through
the StringBuffer class and its append method.
String conversions are implemented through
the method toString, defined by Object and
inherited by all classes in Java.
12/29/08 20
What is the performance impact of
the StringBuffer and String classes?
Java provides the StringBuffer and
String classes, and the String class is
used to manipulate character strings that
cannot be changed.
Simply stated, objects of type String are
read only and immutable.
The StringBuffer class is used to
represent characters that can be
modified.
12/29/08 21
… Continued
In other words, String is an immutable
object and StringBuffer is a mutable
object.
The significant performance difference
between these two classes is that
StringBuffer is faster than String when
performing simple concatenations.
In String manipulation code, character
strings are routinely concatenated.
12/29/08 22
… Continued
Using the String class, concatenations
are typically performed as follows:
String str = new String ("Titanic ");
str += "Lost!!";
12/29/08 23
Constructing a String
If you are constructing a string with several appends, it
may be more efficient to construct it using a
StringBuffer and then convert it to an immutable String
object.
StringBuffer buf = new StringBuffer("Java");
// Append
buf.append(" Tiger v1/"); // Java Tiger v1/
buf.append(5); // Java Tiger v1/5
// Set
int index = 13;
buf.setCharAt(index, '.'); // Java Tiger v1.5
12/29/08 24
… Continued
// Insert
index = 5;
// Replace
int start = 25;
12/29/08 25
… Continued
// Delete
start = 22;
end = 23;
// Convert to string
String s = buf.toString();
12/29/08 26
Convert a String to Boolean
The following program converts strings like true, false, yes, no, 1, and 0
to a java boolean variable.
The program is as follows:
public class BoolUtility
{
public static final boolean stringToBoolean(String str)
{
if (str.equals("0")) return false;
str = str.toLowerCase();
if (str.equals("false")) return false;
if (str.equals("no")) return false;
12/29/08 27
… Continued
public static void main(String args[])
{
if (args.length > 0)
{
if (BoolUtility.stringToBoolean(args[0]))
System.out.println(args[0] + " is TRUE");
else
System.out.println(args[0] + " is FALSE");
}
else
System.out.println("Run the program with a
bool to test");
}
}
12/29/08 28
… Continued
C:\>javac BoolUtility.java
C:\>java BoolUtility
Run the program with a bool to test
C:\>java BoolUtility 1
1 is TRUE
C:\>java BoolUtility 0
0 is FALSE
12/29/08 29
What is StringTokenizer?
java.util.StringTokenizer
The string tokenizer class allows an
application to break a string into tokens.
The StringTokenizer methods do not
distinguish among identifiers, numbers, and
quoted strings, nor do they recognize and skip
comments.
The set of delimiters (the characters that
separate tokens) may be specified either at
creation time or on a per-token basis.
12/29/08 30
… Continued
12/29/08 31
… Continued
The following is one example of the use of the tokenizer.
import java.util.StringTokenizer;
class STokenTest
{
public static void main(String[] args)
{
StringTokenizer st = new
StringTokenizer("this is a test");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
12/29/08 32
… Continued
C:\>javac STokenTest.java
C:\>java STokenTest
this
is
a
test
C:\>
12/29/08 33
… Continued
12/29/08 34
… Continued
The following example illustrates how the String.split
method can be used to break up a string into its basic
tokens:
class StrSplit
{
public static void main(String[] args)
{
String[] result = "this is a
test".split("\\s");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
}
}
12/29/08 35
… Continued
C:\>javac StrSplit.java
C:\>java StrSplit
this
is
a
test
C:\>
12/29/08 36
URLs
http://www.allapplabs.com/java/java.htm
http://javaalmanac.com/egs/java.lang/pkg.htm
12/29/08 37
Thank You…
12/29/08 38