0% found this document useful (0 votes)
221 views56 pages

Arrays and Strings

Arrays allow storing multiple values of the same type using a single name and index. In Java, arrays must be declared with a type and allocated with new. Elements are accessed using square brackets and numeric indexes starting from 0. The length property returns the array's size. Arrays can be passed to and returned from methods. The Arrays class provides utility methods for sorting, searching, copying, and filling arrays.

Uploaded by

AAsfaw
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
221 views56 pages

Arrays and Strings

Arrays allow storing multiple values of the same type using a single name and index. In Java, arrays must be declared with a type and allocated with new. Elements are accessed using square brackets and numeric indexes starting from 0. The length property returns the array's size. Arrays can be passed to and returned from methods. The Arrays class provides utility methods for sorting, searching, copying, and filling arrays.

Uploaded by

AAsfaw
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 56

Arrays and

Strings

1
Array
Overview
0The basic solution. Arrays are the basic way to store large numbers
of values. Every programming language you're likely to use has arrays
as part of the fundamental language, although with many little
variations on how they work.
0Strings are like arrays of chars and you should be familiar with the
idea of storing multiple values which are accessed by a numeric index.
0Other possibilities. Arrays in Java are great for working with a fixed
numbers of elements, but Java also has the Collections library of classes
that are a better choice when working with a variable number of
objects, eg,ArrayList, but it's essential to learn about arrays, so we'll
start with them.
Arrays store many values using one name and an index
0An array can store many similar values in memory. Each value is
accessed by specifying an integer subscript orindex in brackets
following the array name. "Array" in Java means approximately the
same thing as array,matrix, or vector does in math. Unlike math and
some other programming languages, in Java you must both declare an
array and allocate a fixed amount of memory for it. 2
Array(cont)
Declaring an array
0An array variable is like other variables -- you must declare it, which
means you must declare the type of elements that are in an array. All
elements must be the same type. Write the element type name, then
"[]", then the name of the array variable. The declaration allocates only
enough space for a reference to an array (typically 4 bytes), but
doesn't create the actual array object.
DataType[] nameOfArray;
String[] args; // args is an array of Strings
int[] scores; // scores is an array of ints

0No size in declaration. Unlike some languages, never put the size of


the array in the declaration because an array declaration specifies only
the element type and the variable name. The size is specified when you
allocate space for the array. 3
Array(cont)
Allocate an array object with new
0Create an array using new. This example creates an array of 100 int
elements, from a[0] to a[99].
int[] a; // Declare a to be an array of ints
a = new int[100]; // Allocate an array of 100 ints

These are often combined in one line.


int[] a = new int[100]; // Declare and allocate.

4
Array(cont)
Subscripts (indexes/indices)
0Subscripts are enclosed in square brackets []. xi in mathematics is x[i] in Java,
and is pronounced "x-sub-i".
0Subscript ranges always start at zero because Java came largely from C++,
which had a good reason for using zero (pointer arithmetic on arrays). It isn't the
way that humans normally count; you'll just have to live with it.
0Java always checks subscript legality to be sure the subscript is >= 0, and less
than the number of elements in the array. If the subscript is outside this range,
Java throws ArrayIndexOutOfBoundsException. This is far superior to the behaver
of C and C++, which allow out of range references. Consequently, Java programs
are far less susceptible to bugs and security flaws than C/C++ programs.
0Zero-based indexing is a constant annoyance of Java's zero-based indexing. The
natural human value for hours or days should be used as an index to make the
program most readable, but this would mean starting with 1, not zero.
0Translate or ignore 0 element? If the data you are working with naturally
starts at one, not zero, either the data must be modified before using it as an
index, or the size of the array could be increased by one row so that the natural
values could be used, and row 0 would never be referenced. Ignoring the zeroth
array element instead of translating data to be zero based is a style decision, and
you'll find various positions on this matter.
5
Array(cont)
Length of an array
0Each array has a constant (final) instance variable that has its length.
You can find out how many elements an array can hold by writing the
array name followed by .length. In the previous
example, a.length would be 100. Remember that this is the number of
elements in the array, one more than the maximum subscript.
Processing Arrays:
0When processing array elements, we often use either for loop or foreach
loop because all of the elements in an array are of the same type and the size
of the array is known.

Example:
0Here is a complete example of showing how to create, initialize and process
arrays:

6
Array(cont)
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5}; Output
// Print all the array elements 1.9
for (int i = 0; i < myList.length; i++) {
2.9
System.out.println(myList[i] + " ");
3.4
}
// Summing all elements
3.5
double total = 0; Total is 11.7
for (int i = 0; i < myList.length; i++) { Max is 3.5
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
} 7
Array(cont)
Initial array element values -- zero/null/false
0When an array is allocated (with new), all elements are set to an
initial value. The initial value is 0 if the element type is numeric (int,
float, ...), false for boolean, and null for all object types.

Array Initialization
0When you declare an array, you can also allocate a pre initialized
array object in the same statement. In this case, do not give the array
size because Java counts the number of values to determine the size.
For example,
String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

8
Array(cont)
Array diagrams
0This code declares and initializes an array.
int[ ] a = {1, 2, 4, 8, 16};
0Arrays are often represented with diagrams that represent their memory
use. The diagrams below are typical ways to represent the memory used by
an array.
0Each box represents the amount of memory needed to hold one array
element. For ints this is 4 bytes. The array variable, a, is a reference (ie,
memory address in the heap) of the block of memory that holds the actual
array elements. References are often represented by a black disk with an
arrow pointing to the data they reference. Most often array diagrams are
written vertically, but sometimes the cells are arranged horizontally,
especially for arrays of characters. Of course in the actual physical memory
there is no such idea as vertical or horizontal.

9
Array(cont)

10
Array(cont)
Array variables are references to a block of elements
0When you declare an array variable, Java reserves only enough memory
for a reference (Java's name for anaddress or pointer) to an array object.
References typically require only 4 bytes. When an array object is created
with new, a reference is returned, and that reference can then be assigned
to a variable. When you assign one array variable to another, only the
reference is copied. For example,
int[] a = new int[] {100, 99, 98}; // "a" references the array object.
int[] b; // "b" doesn't reference anything.
b = a; // Now "b" refers to the SAME array as "a"
b[1] = 0; // Also changes a[1] because a and b refer to the same array.

11
Array(cont)
Passing Arrays to Methods:
0Just as you can pass primitive type values to methods, you can also pass arrays
to methods. For example, the following method displays the elements in an int
array:

public static void printArray(int[] array) {


for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
0You can invoke it by passing an array. For example, the following statement
invokes the printArray method to display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
Or
int[] a = {2,4,6};
printArray(a); 12
Array(cont)
Returning an Array from a Method:
0A method may also return an array. For example, the method shown below
returns an array that is the reversal of another array:

public static int[] reverse(int[] list) {


int[] result = new int[list.length];
for (int i = 0; i = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}

13
Array(cont)

14
Array(cont)
Array Library Methods
0Static methods for manipulating arrays are available in
the java.util.Arrays and java.System classes. Assume the following declarations,
where T is the array element type, either a primitive, object or either kind of
type depending on which method is being called.

15
Array(cont)
lst = Arrays.asList(a); List based on the array.
s = Arrays.toString(a); String form surrounded by "[]", elements
separated by ", ".
s = Arrays.deepToString(a); String form by recursively converting
subarrays.
b = Arrays.equals(a, a2); True if arrays are same size and all
elements are equal (== or equals as
appropriate).
b = Arrays.deepEquals(a, a2); As above, recursively applied to
subarrays.
Arrays.fill(a, x); Fills array with a value.
Arrays.fill(a, from, to, x); Fills subrange
(from inclusive, to exclusive) with a value.
Making a copy of part of an array
System.arraycopy(a, i1, a2, i2, len); Shallow copy len elements
from a[i1] to a2[i2]. Case!
a2 = Arrays.copyOf(a, newLength); New shallow copy of array with new
length. If longer, uses default values.
a2 = Arrays.copyOfRange(a, from, to); New shallow copy of portion of array.16
Array(cont)
Searching
i = Arrays.binarySearch(a, key); A O(log N)search of array sorted in
ascending order. If the key is not
found, a negative number,
-insertionPoint-1, is returned.
i = Arrays.binarySearch(a, key, comp); Binary search of a sorted array of
objects (not primitives).
Sorting
Arrays.sort(a); Sorts in "natural" order. If object
type, elements must becomparable.
Arrays.sort(a, comp); Sorts objects (not primitives) using
comparator.
Arrays.sort(a, from, to); Sorts subrange,
including a[from] excluding a[to].
Arrays.sort(a, from, to, comp); Sorts objects (not primitives) in
subrange using comparator.

17
Array(cont)
Use java.util.Arrays.toString(...) for debugging
0AVOID default toString(). Using the common debugging technique of
printing intermediate values on the console with arrays is good, but requires
calling a library method to get the results you expect. Arrays are a subclass
of Object as ever other object is, and therefore the toString() method is defined
for every array. The results will very likely disappoint you.
String[] abc = {"a", "b", "c"};
System.out.println(abc); // println calls toString() on object parameters.
This displays the relatively unhelpful "[L", element type, ";@", and
hexadecimal memory address of the array.
[Ljava.lang.String;@f6f1b6
0USE java.util.Arrays.toString(...) and you'll get something much more
readable. An import java.util.*; statement avoids the extra package qualifier.
String[] abc = {"a", "b", "c"};
System.out.println(java.util.Arrays.toString(abc));
This produces the following output, which is the same as toString() applied
to a List. Output : [a, b, c] 18
Array(cont)
Use Arrays.asList(...) for Collections view of array
0Make a list. The Arrays class has some useful methods for working with
arrays, but there are a lot more if you make your array look like a List. The
Collections class has many useful methods, eg, shuffle, reverse, max, ....
import java.util.*;
...
List<String> listabc = Arrays.asList(abc);
// The Collections methods can now be use with listabc.
0View of underlying array. The list that is created is not a regular ArrayList. It
is based only on the original array, so you can't do things like adding elements
to the list because this would cause reallocation of a larger underlying array.
0Uses the underlying array. One of the really nice things about this is that you
can still use the underlying array, which means that creating this list doesn't
prevent you from taking advantage of the efficiency of array access for example.
0Objects only. The java.util.Arrays.asList(...) method only works for arrays of
object types. If you try to use it with an array of primitives, you will get a
compilation error.

19
Array(cont)
Shuffling (randomizing) an array
import java.util.*;
...
List<String> labc = Arrays.asList(abc);
...
Collections.shuffle(labc);
System.out.println(labc);
//Which gave the following output. Note that the List overrides toString() to
//give reasonable output. [b, a, c]
0Inefficient? Not necessarily. Constructing a new List object from the array is only
inefficient if you're doing it frequently. If you do it very often then you want to avoid
creating a new list each time. Creating the list one time is not a problem because the
list that is produced is backed by this one array -- you can change elements in the
array and the list will reflect those changes.
0Can't shuffle arrays of primitives this way! Lists and other Collections classes
only work on objects, not on primitive values, so you have to do the shuffling "by
hand".
0Commentary A shuffle(...) method that works with primitive types should be
added to the Arrays class.
20
Arrays - 2-dimensional
1-, 2-, and higher-dimensional arrays
0Java, as with most languages, supports multi-dimensional arrays - 1-
dimensional, 2-dimensional, 3-dimensional, ... In practice most arrays are one-
dimensional, and two-dimensional (rows and columns) are also quite common.
Higher dimensional arrays are less common so they aren't used in the
examples, but there's nothing mysterious about them and the same principles
apply.
0Two-dimensional arrays are used whenever the model data is best
represented with rows and columns, or has two varying aspects (eg, gender
and age, weight and height, ...). It's also the idea, although not the
implementation, of graphics that specifies a two (or three) dimensional
position with an x and y (and z) coordinate.
0Terminology. Other terms you will see for a two-dimensional array
are matrix or table.

21
Arrays - 2-dimensional(C)
Visualizing two-dimensional arrays
02-dimensional arrays are usually represented with a row-column
"spreadsheet" style. Assume we have an array, a, with two rows and four
columns.
int[][] a = new int[2][3]; // Two rows and three columns.

0Two-dimensional arrays are usually visualized as a matrix, with rows and


columns. This diagram shows the array a with its corresponding subscripts.

22
Arrays - 2-dimensional(C)
Style: Use constants for the array sizes
0It's very useful to define constants for the number of rows and columns.
static final int ROWS = 2;
static final int COLS = 3;
...
int[][] board = new int[ROWS][COLS];
0Many row and column indexes (indices is the traditional English plural) have a
meaning, and aren't just simply arbitrary numbers. The following example might be
used to represent the number of accidents on by day of the month and the hour of
the day. See programming problems below for some examples using this array.
static final int DAYS = 31;
static final int HOURS = 24;
...
int[][] accidents = new int[DAYS][HOURS];
Initial values
0You can assign initial values to an array when in a manner very similar to one-
dimensional arrays, but with an extra level of braces. The dimension sizes are
computed by the compiler from the number of values. This would allocated a 3x3
board
23
0int[][] board = new int[][] {{1,0,0,3},{0,1,0,5},{1,2,1,6}};
Two-dimensional arrays as arrays of
arrays
Arrays of arrays
0Java builds multi-dimensional arrays from many one-dimensional arrays, the
so-called "arrays of arrays" approach.
0There are a couple of interesting consequences of this: Rows may be different
sizes. Also, each row is an object (an array) that can be used independently.
Multi-dimensional arrays are built from multiple one-dimensional arrays
0As with all arrays, the new keyword must be used to allocate memory for an
array. For example,
int[][] a = new int[2][4];
This two-dimensional array will have two rows and four columns.
0This actually allocates 3 objects: a one-dimensional array of 2 elements to hold
each of the actual row arrays, and a two one-dimensional arrays of 4 elements
to represent the contents of the rows.

24
Two-dimensional arrays as arrays of
arrays(c)
In Java two-dimensional arrays are implemented is a one-dimensional array of
one-dimensional arrays -- like this.

25
Two-dimensional arrays as arrays of
arrays(c)
Processing 2-dimensional arrays using .length
0Notice in the following example how the rows are handled as separate objects.
For example,
int[][] a2 = ...;
// Print array even though we don't know the original size.
for (int r=0; r < a2.length; r++) {
for (int c=0; c < a2[r].length; c++) {
System.out.print(" " + a2[r][c]);
}
System.out.println("");
}

26
Two-dimensional arrays as arrays of
arrays(c)
Trick: Ignoring the zeroth row
0Sometimes you want to use natural input values as an index, the real values
that that data has instead of starting with zero. Let's take the case of data that
starts with the value 1, like the day of the month. The standard approach is to
subtract one from every day value that's used as an index. This is annoying and
error prone. Another way to do handle this case is to declare the array with an
extra element, eg, 32 if dealing with the days in the month, then ignoring the
zeroth element. If you're dealing with a two dimensional array, for example
theaccidents array from the previous page, you can even deallocate the first
row so there won't be any possibility of referencing the zeroth day. For
example,
static final int DAYS = 32;
static final int HOURS = 24;
...
int[][] accidents = new int[DAYS][HOURS];
accidents[0] = null;
Because two-dimensional arrays are stored by row, you can do this. You
can use the trick of allocating more columns to use the natural data, but you 27
can't deallocate a column.
Two-dimensional arrays as arrays of
arrays(c)
Ragged arrays - Uneven rows
0One consequence of arrays of arrays is that each row can be a different size.
For example, we could create a lower triangular array, allocating each row "by
hand" as follows. Note how new can be used with only the row dimension.

28
Arrays More(cont)
 C-style array declarations
0Java also allows you to write the square brackets after the variable
name, instead of after the type. This is how array declarations are
written in C, but is not a good style for Java. C declaration syntax can get
very ugly with part of the declaration before the variable, and part after.
Java has a much nicer style where all type information can be written
together. There are times when only the Java notation is possible to use.
int[] a; // Java style -- good
int a[]; // C style -- legal, but not Java style

29
String
String Overview
0Strings are sequences of Unicode characters.
0In many programming languages strings are are stored in arrays of
characters. However, in Java strings are a separate object type, String.
0The "+" operator is used for concatenation, but all other operations on
strings are done with methods in the String class.

30
String(cont)
String literals
0To write a constant string, put the characters between double
quotes, eg "abc".
Escape Character
0There are some characters that can't be written directly in a string.
The backslash ('\') character precedes any of these special characters.
For example, if a string contains a double quotes, put a backslash ('\')
in front of each internal double quote, eg "abc\"def\"ghi". The other
most common escape character is the newline character, which is
written as "n" following the backslash. For example, the following
string will produces two output lines. Note that the compiler replaces
the backslash plus character with the one desired character.
Eg, "\n".length()is one.
System.out.println("This is the first\nand this is the second line.");
The "empty" string
0The String equivalent of 0, is the string with no characters, "".
31
Concatenation
String(cont)

0Putting two strings together to make a third string is called concatenation. In


Java the concatenation operator is '+', the same operator as for adding
numbers. If either operand is a String, Java will convert the other operand to a
String (if possible) and concatenate the two.
Upper- and lowercase
0To change to uppercase (and similarly to lowercase), Java has two methods,
depending on whether you have a single character (eg, c) or a String (eg, s).
Converting a string to uppercase
s = s.toUpperCase();
Converting a character to uppercase
c = Character.toUpperCase(c);
Of course, you don't have to assign these values back to themselves -- you 32
can
use the values where you want.
String(cont)
String Comparison
0Strings can not be compared with the usual <, <=, >, or >= operators,
and the == and != operators don't compare the characters in the
strings.
Comparing Strings: ==, .equals(), .compareTo(), ...
0To compare Strings for equality, don't use ==. The == operator checks
to see if two objects are exactly the same object. Two strings may be
different objects, but have the same value (have exactly the same
characters in them). Use the .equals() method to compare strings for
equality. Similarly, use the .compareTo() method to test for unequal
comparisons. For example,
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT
33
String methods
These are common String methods. In all of these prototypes, 

0i and j are int indexes into a string, 


0s and t are Strings,  
0c is a char. 
0cs is a CharacterSequence (eg, either String or StringBuilder).

34
String methods
Length
i = s.length() length of the string s.
Comparison (note: use these instead of == and !=)
i = s.compareTo(t) compares to s. returns <0 if
s<t, 0 if ==, >0 if s>t
i = s.compareToIgnoreCase(t) same as above, but upper
and lower case are same
b = s.equals(t) true if the two strings have
equal values
b = s.equalsIgnoreCase(t) same as above ignoring case
b = s.startsWith(t) true if s starts with t
b = s.startsWith(t, i) true if t occurs starting at
index i
b = s.endsWith(t) true if s ends with t

35
String methods
Searching -- Note: All "indexOf" methods return -1 if the
string/char is not found
i = s.contains(cs) True if cs can be found in s.
i = s.indexOf(t) index of the first occurrence
of String t in s.
i = s.indexOf(t, i) index of String t at or after
position i in s.
i = s.indexOf(c) index of the first occurrence
of char c in s.
i = s.indexOf(c, i) index of char c at or after
position i in s.
i = s.lastIndexOf(c) index of last occurrence
of c in s.
i = s.lastIndexOf(c, i) index of last occurrence
of c on or before i in s.
i = s.lastIndexOf(t) index of last occurrence
of t in s.
i = s.lastIndexOf(t, i) index of last occurrence
of t on or before i in s.
36
String methods
Getting parts
c = s.charAt(i) char at position i in s.
s1 = s.substring(i) substring from index i to the
end of s.
s1 = s.substring(i, j) substring from index i to
BEFORE index j of s.
Creating a new string from the original
s1 = s.toLowerCase() new String with all chars
lowercase
s1 = s.toUpperCase() new String with all chars
uppercase
s1 = s.trim() new String with whitespace
deleted from front and back
s1 = s.replace(c1, c2) new String with
all c1 characters replaced by
character c2.
s1 = s.replace(cs2, cs3) new String with
all cs2 substrings replaced
by cs3. 37
String methods
Regular Expressions (as of Java 1.4) regexStr parameters are Strings, but see
also java.util.regex.Pattern, ...
b =  s.matches(regexStr) true if regexStr matches the entire string in
s. Same as Pattern.matches(regexStr, s)
s1 =  s.replaceAll(regexStr, t) replaces each substring that
matches regexStr with String t
s1 =  s.replaceFirst(regexStr, t) replaces first substring that
matches regexStr with String t
sa =  s.split(regexStr) array of all substrings terminated
by regexStr or end
sa =  s.split(regexStr, count) limited to
applying regexStr only count times.
Static Methods for Converting to String
s =  String.valueOf(x) Converts x to String, where x is any type
value (primitive or object).
s =  String.format(f, x...) [Java 5] Use format f to convert variable
number of parameters, x to a string.
Comparator for sorting arrays and collections.
comp =  String.CASE_INSENSITIVE_ORDER A static Comparator object that does case-
insensitive comparisons for sorts and ordered
Collections (eg, TreeMap, TreeSet, 38
SortedMap, and SortedSet).
Summary
- java.util.StringBuilder and java.util.StringBuffe
r
0 Strings are immutable (can't be changed), so manipulating
strings often causes many temporary string objects to be
created, which can be quite inefficient. StringBuilder (or
StringBuffer) are better choices in these cases.
Their toString() method can be used get a String value. It
isn't necessary to create them with a specific size, it will
expand as necessary. Many StringBuilder methods return the
same StringBuilder so that the call chaining style of
programming can be used.
0 StringBuilder is basically identical to the older StringBuffer,
but is slightly faster because it isn't synchronized.

39
Summary
- java.util.StringBuilder and java.util.StringBuffe
Constructors
r
sb = new StringBuilder() Creates empty StringBuilder

sb = new StringBuilder(n) Creates empty StringBuilder with initial


capacity n.
sb = new StringBuilder(s) Creates StringBuilder with value initialized to
String s.
Length
i = sb.length() Length of the current contents of sb.
Modifying the content - These methods return the original StingBuilder to allow
call chaining.
sb =sb.append(x) Appends x (char, int, String, ...) to end of sb.

sb =sb.insert(offset, x) Inserts x (char, int, String, ...) at


position offset.
sb =sb.setCharAt(index, c) Replaces char at index with c
sb =sb.deleteCharAt(i) Deletes char at index i.
sb =sb.delete(beg, end) Deletes chars at index beg thru end.
sb =sb.reverse() Reverses the contents.
40
sb =sb.replace(beg, end, s) Replaces characters beg thru end with s.
Summary
- java.util.StringBuilder and java.util.StringBuffe
Getting parts
r
c = sb.charAt(i) char at position i in sb.

s = sb.substring(i) substring from index i to the end of sb.

s = sb.substring(i, j) substring from index i to BEFORE


index j of sb.
Misc
s = sb.toString() Returns a String for the contents of sb.
Searching -- Note: All "indexOf" methods return -1 if the string/char is not
found
i = sb.indexOf(s) index of the first occurrence of String s in s.

i = sb.indexOf(s, i) index of String s at or after position i in sb.

i = sb.lastIndexOf(s) index of last occurrence of s in sb.


i = sb.lastIndexOf(s, i) index of last occurrence of s on or
before i in sb.
Comparison (note: use this instead of == and !=)
b = sb.equals(sb2) 41
true if the two StringBuilders contain equal
values
Converting Numbers to Strings
Number to string conversion alternatives
0Concatenation (+): Anything concatenated to a string is
converted to string (eg, "weight = " + kilograms).
0java.text.DecimalFormat gives you precise control over the
formating of numbers (number of decimal places, scientific
notation, locale formatting, ...).
0Individual wrapper class methods, eg, Integer.toString(i).
concatenation works as well for the simple cases, but there are
some interesting additional conversions here.
0printf(), added in Java 5, uses a format for conversion.
0No conversion required. Some common system methods will
take any type and convert it, eg,System.out.println().

42
Converting Numbers to Strings
Concatenation (+)
0The most common idiom to convert something to a string is to
concatenate it with a string. If you just want the value with no
additional text, concatenate it with the empty string, one with no
characters in it ("").
0If either operand of a concatenation is a string, the other operand is
converted to string, regardless of whether it is a primitive or object
type.
int x = 42;
String s; s = x; // ILLEGAL
s = "" + x; // Converts int 42 to String "42"
s = x + " is OK"; // Assigns "42 is OK" to s.
s = "" + 3.5; // Assigns "3.5" to s
s = "" + 1.0/3.0; // Assigns "0.3333333333333333" to s
0Precision. The problem with floating-point numbers by concatenation
is that you have no control over the number of decimal places the
conversion chooses for you, as you can see in the above example.
43
Converting Numbers to Strings
java.text.DecimalFormat
0The java.text.DecimalFormat class provides many ways to format
numbers into strings, including number of fraction digits, using a
currency symbol ($12.35), scientific notation (3.085e24), percentage
scaling (33%), locale which defines national formatting options
(3,000.50 or 3.000,50 or 3'000,50 or ...), patterns for positive, zero, and
negative numbers, etc. These notes show only how to specify the
number of fraction digits. Check the Java API documentation for other
options.
0First, create a DecimalFormat object which specifies the format of the
number. The zero before the decimal point means that at least one digit
is produced, even if it is zero. The zeros after the decimal point specify
how many fraction digits are produced. Then call the format() method
of that object, passing the numeric value to be converted.
0The string that is returned by the format() will not contain additional
text, other than an optional currency or percent sign. Specifically, it can
not be used to pad numbers on the left with blanks for use in right
alignment of a column of numbers. Use printf() for this.
0This program uses the same formatting object many times.
44
Converting Numbers to Strings
java.text.DecimalFormat

45
Converting Numbers to Strings
Rounding by the half even algorithm
0Floating-point numbers may be rounded when they are converted to
string (default conversion, DecimalFormator the Math.round method,
etc). Rounding uses the half even method which rounds
 To the nearest neighbor.
 If the number is exactly between its neighbors, it is rounded to
its even neighbor. The reason middle values are rounded to the
even value, instead of up as is commonly done, is to prevent an
accumulation of errors.
0Examples rounding to an integer: 3.1 rounds to 3, 3.8 rounds to 4, 3.5
rounds to 4, but 4.5 also rounds to 4, 5.5 rounds to 6.

46
Converting Numbers to Strings
StringBuffer and StringBuilder append() methods - like concatenation
0The most efficient way to build strings from parts is to use StringBuffer (all
versions, synchronized), or the essential identical StringBuilder (Java 5,
unsynchronized and therefore slightly faster than StringBuffer). Their
many append() methods take numbers and perform default conversions to
string before appending them to their current value.

47
Converting Numbers to Strings
Numeric objects: Integer, Double, BigDecimal, BigInteger, ...
0Concatenation works with all objects, not just numbers. When Java needs to
convert an object to a String, it calls the object's toString() method. Because
every class (object type) has the class Object as an ancestor, every class
inherits Object's toString() method. This will do something to generate a
string from an object, but it will not always be very useful. Many classes
override toString() to do something better. When you write a class whose
objects might be converted to a String, write a toString method.
printf()
0Java 5 added the format() and printf() methods to various classes. These
convert number according to a format string. 

48
Converting Anything to String
0 Summary: Converting any data to strings is easy. You can do almost
everything with concatenation, but can get more control using some of the
alternatives.
Summary of conversion alternatives
0 Concatenate anything to a string and it will automatically be converted to
string and then the concatenation will take place.
0 Call toString() for an object. This method will convert any object into a
string, altho it won't always produce the result you want.
0 Use formatted output, eg by calling String.format(...). See 
Formatted conversion to String .
0 No conversion is required by some common system methods, which take
any type parameter and convert it to a String, eg, System.out.println().

49
Converting Anything to String
Concatenation (+)
0The most common idiom to convert something to a string is to concatenate it
with a string. If you just want the value with no additional text, concatenate it
with the empty string, one with no characters in it ("").
0If either operand of a concatenation is a string, the other operand is
converted to string, regardless of whether it is a primitive or object type.

50
Converting Anything to String
toString() method - Define it for your classes
0Method toString is already defined. When Java needs to convert an object
to a String, it calls the object'stoString() method. Because every class (object
type) inherits from the Object class, Object's toString()method is
automatically defined. This generates a string from an object, but it will not
always be very useful. If the child class doesn't override toString(), the default
probably won't print anything interesting. Just as many of the Java library
classes override toString() to produce something more useful, you should also
overridetoString() in your classes.

51
Converting Strings to Numbers
0 To convert a string value to a number (for example, to convert the String
value in a text field to an int), use these methods. Assume the following
declarations:
0 String s; int i; long l; float f; double d;

0 If s is null or not a valid representation of a number of that type, these


methods will throw (generate) aNumberFormatException.

52
Converting Strings to Numbers
Handling NumberFormatExceptions
0Put number conversions inside a try . . . catch statement so that you can do
something if bad input is entered. The conversion method will throw a
NumberFormatException when there is bad input. Catch the
NumberFormatException, and do something to handle this error condition. Put
your conversion in the try clause, and the error handling in the catch clause.
Here is an example of the kind of utility function you might write to do this
checking.

53
Converting Strings to Numbers
Handling NumberFormatExceptions
public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
Scanner scan = new Scanner(System.in);
String s = scan.next();
try {
val = Integer.parseInt(s);
break; // exit loop with valid int
>>>>>>>>>>>>>>>>>>>>>>
}catch (NumberFormatException nx) {
System.out.println("Enter valid integer");
}
}
return val;
54
}//end getInt
Converting Strings to Numbers
Non-decimal Integers
0Convert integers with some base (radix) other than 10 by using these two
methods. Typically these will be hexadecimal (base 16) or binary (base 2)
numbers.

0For example, to convert a string containing the hexadecimal number "F7" to


an integer, call
i = Integer.parseInt("F7", 16)

55
End

56

You might also like