Download Arrays and Strings

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Arrays and Strings
•
•
•
•
•
An array is a collection of variables of the same type,
referred to by a common name.
In Java arrays can have one or more dimensions,
although the one-dimensional array is the most common.
Arrays are used for a variety of purposes because they
offer a convenient means of grouping together related
variables.
The principal advantage of an array is that it organizes
data in such a way that it can be easily manipulated.
In Java arrays are implemented as objects.
Arrays and Strings
tMyn
1
• This fact is one reason that a discussion of arrays was
deferred until objects had been introduced.
• By implementing arrays as objects, several important
advantages are gained, not the least of which is that
unused arrays can be garbage collected.
• To declare a one-dimensional array, you will use this
general form:
type[] arrayName=new type[size];
• Here, type declares the base type of the array.
• The base type determines the data type of each element
contained in the array.
Arrays and Strings
tMyn
2
• The number of elements that the array will hold is
determined by size.
• Since arrays are implemented as objects, the creation of
an array is a two-step process. First, you declare an
array reference variable. Second, you allocate memory
for the array, assigning a reference to that memory to the
array variable.
• Thus, all arrays in Java are dynamically allocated using
the new operator.
• The following creates an int array of 10 elements and
links it to an array reference variable named sample:
int[] sample=new int[10];
Arrays and Strings
tMyn
3
• This declaration works just like an object declaration.
The sample variable holds a reference to the memory
allocated by new.
• As with objects, it is possible to break the preceding
declaration in two:
int[] sample;
sample=new int[10];
• In this case, when sample is first created, it is null,
because it refers to no physical object. It is only after the
second statement executes that sample is linked with an
array.
Arrays and Strings
tMyn
4
• An individual element within an array is accessed by use
of an index.
• An index describes the position of an element within an
array. All arrays have zero as the index of their first
element.
• Thus, the first element in sample is sample[0].
Arrays and Strings
tMyn
5
package array1;
public class Main
{
public static void main(String[] args)
{
int[] sample=new int[10];
int i;
for(i=0; i<10; i++)
sample[i]=i;
for(i=0; i<10; i++)
System.out.println("This is sample[" +i+"]: "+
sample[i]);
}
}
Arrays and Strings
tMyn
6
run:
This is sample[0]: 0
This is sample[1]: 1
This is sample[2]: 2
This is sample[3]: 3
This is sample[4]: 4
This is sample[5]: 5
This is sample[6]: 6
This is sample[7]: 7
This is sample[8]: 8
This is sample[9]: 9
BUILD SUCCESSFUL (total time: 2 seconds)
Arrays and Strings
tMyn
7
• The following program finds the minimum and maximum
values stored in the nums array by cycling through the
array using a for loop:
Arrays and Strings
tMyn
8
package array2;
public class Main
{
public static void main(String[] args)
{
int[] nums=new int[10];
int min, max;
nums[0]=99;
nums[1]=-10;
nums[2]=100123;
nums[3]=18;
nums[4]=-978;
nums[5]=5623;
nums[7]=-9;
nums[8]=287;
nums[9]=49;
min=max=nums[0];
Arrays and Strings
tMyn
9
for(int i=1; i<10; i++)
{
if(nums[i]<min)
min=nums[i];
if(nums[i]>max)
max=nums[i];
}
System.out.println("min and max: "+min+" and "+max);
}
}
run:
min and max: -978 and 100123
BUILD SUCCESSFUL (total time: 1 second)
Arrays and Strings
tMyn
10
• From the previous example: there is an easier way to
initialize an array:
type[] arrayName={val1, val2, val3, …};
• Initial values are assigned in sequence, left to right, in
index order.
• Java automatically allocates an array large enough to
hold the initializers that you specify.
• There is no need to explicitly use the new operator:
Arrays and Strings
tMyn
11
package array2a;
public class Main
{
public static void main(String[] args)
{
int[] nums={99, -10, 100123, 18, -978, 5623, 463, -9, 287, 49};
int min, max;
min=max=nums[0];
for(int i=1; i<10; i++)
{
if(nums[i]<min)
min=nums[i];
if(nums[i]>max)
max=nums[i];
}
System.out.println("min and max: "+min+" and "+max);
}
}
Arrays and Strings
tMyn
12
• In the next example: the user tells how many elements
are needed in an array. The sum of the elements is also
calculated:
Arrays and Strings
tMyn
13
package TimoSoft;
import java.util.Scanner;
public class PassingArrays
{
int[] someNumbers;
PassingArrays()
{
setArray();
}
void setArray()
{
Scanner fromKeyboard1=new Scanner(System.in);
System.out.print("How many elements would you like to enter?: ");
int index=fromKeyboard1.nextInt();
someNumbers=new int[index];
Scanner fromKeyboard2=new Scanner(System.in);
Arrays and Strings
tMyn
14
for (int i=0; i<index; i++)
{
System.out.print("Enter the element for the "+(i+1)+". time: ");
someNumbers[i]=fromKeyboard2.nextInt();
}
}
void getArray()
{
System.out.println();
for(int i=0; i<someNumbers.length; i++)
System.out.print(someNumbers[i]+" ");
System.out.println();
}
int calculateTotal()
{
int total=0;
for(int counter=0; counter<someNumbers.length; counter++)
total=total+someNumbers[counter];
return total;
}
}
Arrays and Strings
tMyn
15
package TimoSoft;
public class PassingArraysTest
{
public static void main(String[] args)
{
PassingArrays first=new PassingArrays();
first.getArray();
System.out.println("\nThe sum of the elements is "+
first.calculateTotal());
}
}
Arrays and Strings
tMyn
16
run:
How many elements would you like to enter?: 4
Enter the element for the 1. time: 11
Enter the element for the 2. time: 22
Enter the element for the 3. time: 33
Enter the element for the 4. time: 44
11 22 33 44
The sum of the elements is 110
BUILD SUCCESSFUL (total time: 12 seconds)
Arrays and Strings
tMyn
17
• The simplest form of the multidimensional array is the
two-dimensional array.
• A two-dimensional array is, in essence, a list of onedimensional arrays.
• To declare a two-dimensional integer array details of
size 10, 20 (10 rows and 20 columns) you would write
int[][] details=new int[10][20];
• In the next example, a two-dimensional array is loaded
with the numbers 1 through 12:
Arrays and Strings
tMyn
18
package array4;
public class Main
{
public static void main(String[] args)
{
int i, j;
int[][] details=new int[3][4];
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
details[i][j]=(i*4)+j+1;
System.out.print(details[i][j]+" ");
}
run:
}
1 2 3 4 5 6 7 8 9 10 11 12
System.out.println();
BUILD SUCCESSFUL (total time: 0 seconds)
}
}
Arrays and Strings
tMyn
19
• When you allocate memory for a multidimensional array,
you need to specify only the memory for the first
(leftmost) dimension.
• You can allocate the remaining dimensions separately.
• For example, the following code allocates memory for
the first dimension of table when it is declared. It
allocates the second dimension manually:
int[][] irregularArr=new int[3][];
irregularArr[0]=new int[4];
irregularArr[1]=new int[5];
irregularArr[2]=new int[6];
Arrays and Strings
tMyn
20
• The use of irregular (or ragged) multidimensional arrays
is not recommended for most applications, because it
runs contrary to what people expect to find when a
multidimensional array is encountered.
• However, irregular arrays can be used effectively in
some situations.
• Java allows arrays with more than two dimensions.
Arrays and Strings
tMyn
21
• Like other objects, when you assign one array reference
variable to another, you are simply changing what object
that variable refers to.
• You are not causing a copy of the array to be made, nor
are you causing the contents of one array to be copied to
another.
Arrays and Strings
tMyn
22
• From a day-to-day programming standpoint, one of the
most important of Java’s data types is String.
• String defines and supports character strings.
• In some programming languages a string is an array of
characters.
• In Java, strings are objects.
• For example, in the statement
System.out.println(“In Java, strings are
objects!”);
• The string “In Java, strings are objects!” is automatically
made into a String object by Java.
Arrays and Strings
tMyn
23
• Thus, the use of the String class has been “below the
surface” in the preceding programs.
• The String class is quite large.
• You can construct a String just like you construct any
other type of object: by using new and calling the String
constructor:
String str=new String(“Hello from
Mikpoli!”);
• This creates a String object called str that contains
the character string “Hello from Mikpoli!”.
Arrays and Strings
tMyn
24
• You can also construct a String from another String:
String str1=new String(“Hello there!”);
String str2=new String(str1);
• After this sequence executes, str2 will also contain the
character string “Hello there!”.
• Another easy way to create a String object is:
String str3=“This also works OK!”;
Arrays and Strings
tMyn
25
package string1;
public class Main
{
public static void main(String[] args)
{
String str1=new String("Java strings are object.");
String str2="You don't have to use new operator here!";
String str3="And you don't have to call the constructor by name either!";
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}
run:
Java strings are object.
You don't have to use new operator here!
And you don't have to call the constructor by name either!
BUILD SUCCESSFUL (total time: 1 second)
Arrays and Strings
tMyn
26
• Like any other data type, strings can be assembled into
arrays:
Arrays and Strings
tMyn
27
package string2;
public class Main
{
public static void main(String[] args)
{
String[] str={ "Did", "I", "mention", "that", "stuff", "concerning",
"String", "objects?" };
System.out.println("Original array:");
for(int i=0; i<str.length; i++)
System.out.print(str[i]+" ");
System.out.println();
//change a bit
str[1]="you";
str[2]="explain";
System.out.println("Modified array:");
for(int i=0; i<str.length; i++)
System.out.print(str[i]+" ");
System.out.println();
}
}
Arrays and Strings
tMyn
28
run:
Original array:
Did I mention that stuff concerning String objects?
Modified array:
Did you explain that stuff concerning String objects?
BUILD SUCCESSFUL (total time: 0 seconds)
Arrays and Strings
tMyn
29
• Next example: how many names the user of the program
would like to enter?:
Arrays and Strings
tMyn
30
package TimoSoft;
import java.util.Scanner;
public class Names
{
String[] names;
Names()
{
setNames();
}
void setNames()
{
Scanner fromKeyboard1=new Scanner(System.in);
System.out.print("How many names would you like to enter?: ");
int index=fromKeyboard1.nextInt();
names=new String[index];
Arrays and Strings
tMyn
31
Scanner fromKeyboard2=new Scanner(System.in);
for (int i=0; i<index; i++)
{
System.out.print("Enter the name for the "+(i+1)+". time: ");
names[i]=fromKeyboard2.nextLine();
}
}
void getNames()
{
System.out.println();
for(int i=0; i<names.length; i++)
System.out.print(names[i]+" ");
System.out.println();
}
}
Arrays and Strings
tMyn
32
package TimoSoft;
public class NamesTest {
public static void main(String[] args)
{
Names first=new Names();
first.getNames();
}
}
run:
How many names would you like to enter?: 3
Enter the name for the 1. time: Andrew Johnston
Enter the name for the 2. time: Bill McLaren
Enter the name for the 3. time: William Tombstone
Andrew Johnston Bill McLaren William Tombstone
BUILD SUCCESSFUL (total time: 4 minutes 2 seconds)
Arrays and Strings
tMyn
33
• From the preceding example: Do not try to use the same
Scanner object in a situation where you first have read
something with nextInt() and then you try to read
something with nextLine(). It may not work!!
Arrays and Strings
tMyn
34
• The contents of a String object are immutable.
• That is, once created, the character sequence that
makes up the string cannot be altered.
• This restriction allows Java to implement strings more
efficiently.
• When you need a string that is a variation on one that
already exists, simply create a new string that contains
the desired changes.
• Since unused String objects are automatically garbage
collected, you don’t even need to worry about what
happens to the discarded strings.
Arrays and Strings
tMyn
35
• The String reference variables may, of course, change
the object to which they refer.
• It is just that the contents of a specific String object
cannot be changed after it is created.
Arrays and Strings
tMyn
36