You are on page 1of 38

Core Java Programming

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

 The Java array depicted above has 7 elements. Each element in


an array holds a distinct value.
 In the figure, the number above each element shows that
element's index. Elements are always referenced by their indices.
 The first element is always index 0. Hence, the first element is
always index 0.
 Given this zero-based numbering, the index of the last element in
the array is always the array's length minus one.
 So in the array pictured above, the last element would have index
6 because 7 minus 1 equals 6.

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

 An alternate shortcut syntax is available


for declaring and initializing an array.
The length of the array is implicitly
defined by the number of elements
included within the { }.
 An example:
 String[]flintstones = {"Fred",
"Wilma", "Pebbles"};

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

 In most cases, a program will not know


which elements in an array are of
interest.
 Finding the elements that a program
wants to manipulate requires that the
program loop through the array with the
for construct and examine each element
in the array.

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"};

 //use the length attribute to get the number


 //of elements in an array
 for(int i = 0; i < months.length; i++ )
 {
 System.out.println(months[i]);
 }
 }
 }

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"};

 // Shortcut syntax loops through array months


 // and assigns the next element to variable month
 // for each pass through the loop
 for(String month: months)
 {
 System.out.println(month);
 }
 }
 }

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

 The class String includes methods for


examining individual characters of the
sequence, for comparing strings, for
searching strings, for extracting
substrings, and for creating a copy of a
string with all characters translated to
uppercase or to lowercase.

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

 Every string buffer has a capacity. As


long as the length of the character
sequence contained in the string buffer
does not exceed the capacity, it is not
necessary to allocate a new internal
buffer array. If the internal buffer
overflows, it is automatically made
larger.

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!!";

 If you were to use StringBuffer to


perform the same concatenation, you
would need code that looks like this:
 StringBuffer str = new StringBuffer
("Titanic ");
 str.append("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;

 buf.insert(index, "Developers "); //


Java Developers Tiger v1.5

 // Replace
 int start = 25;

 int end = 26;

 buf.replace(start, end, "4"); // Java


Developers Tiger v1.4

12/29/08 25
… Continued
 // Delete
 start = 22;

 end = 23;

 buf.delete(start, end); // Java


Developers Tiger 1.4

 // 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;

 //if it's non false, it's true by definition


 return true;
 }

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

 C:\>java BoolUtility yes


 yes is TRUE

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

 An instance of StringTokenizer behaves


in one of two ways, depending on
whether it was created with the
returnDelims flag having the value true
or false:
 If the flag is false, delimiter characters serve
to separate tokens.
 If the flag is true, delimiter characters are
themselves considered to be tokens.

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

 StringTokenizer is a legacy class that is


retained for compatibility reasons
although its use is discouraged in new
code.
 It is recommended that anyone seeking
this functionality use the split method of
String or the java.util.regex package
instead.

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

You might also like