Download String

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
Array Declarations
• Arrays contain a fixed number of variables of
identical type
• Array declaration and allocation are separate
operations
• Declaration examples:
int[] counts;
double[] scores;
String[] studentNames;
Array Allocation
• Arrays are allocated using the Java new
operator
• The syntax is:
new type[size];
• Examples:
counts = new int[10];
scores = new double[15];
studentNames = new String[10];
Array Organization
0
1
2
3
4
5
6
7
8
9
counts
• Each box is an int variable
• The numbers on top are each variable’s
subscript or index
• An array of size 10 has subscripts 0 to 9
Array Subscripts
• Arrays can contain any one type of value
(either primitive values or references)
• Subscripts are used to access specific array
values
• Examples:
counts[0]
counts[1]
counts[9]
counts[10]
//
//
//
//
//
first variable in counts
second variable in counts
last variable in counts
error – trying to access
variable outside counts
Expressions as Subscripts
• Array subscripts do not have to be constants
• Array subscripts do need to be integer
expressions that evaluate to valid subscript
values for the current array allocation
• Examples:
counts[i]
counts[2*i]
counts[I/2]
Array Initialization
• Arrays can be initialized by giving a list of
their elements
• If your list contains n elements the subscripts
will range from 0 to n – 1
• You do not need to allocate the array
explicitly after it is initialized
• Example:
int [] primes =
{2, 3, 5,
7, 11, 13, 17, 19, 23, 29};
Initializing an Array of Strings
final Sring[ ] NAME = {
“Sunday”, “Monday”, “Tuesday”,
“Wednesday”, “Thursday”, “Friday”,
“Saturday”};
// procedure that prints the day of week
public void printName (int day,
OutputBox out) {
out.print(NAME[day – 1]);
}
Aliases
• It is possible to have two different variables refer to
the same array
• When this happens these variables are called aliases
• Creating aliases is not a good programming practice
• Example of how it can happen:
int [ ] A, B;
…
B = new int [10];
A = B;
Loops and Array Processing
• Initializes counts to 0, 10, 20, … , 90
for (int i=0; i < 10; i++) {
counts[i] = i * 10;
}
• Prints the contents of counts using length
for (int i=0; i < counts.length; i++) {
out.println(counts[i]);
}
Extra Capacity Array
• Arrays cannot grow after they have been
allocated
• You can allocate more space than you
believe your application will need
• If you guess too low, you will still run out of
space
• You do not need to use all the elements in an
array (but total computer memory is finite)
Searching
• This loop terminates as soon as it finds the value 90
stored in grades
bool found = false;
int i = 0;
while (i < size && !found) {
// 90 is not in grades[0]..grades[i - 1]
if (grades[i] == 90)
found = true;
else
i++;
}
Processing Parallel Arrays
• This loop counts the number of students
whose performance improved from the first
test to the second
int improved = 0;
for (int i = 0; i < size; i++) {
if (grades1[i] < grades2[i])
improved++;
}
Arrays of Objects
• Arrays of objects are declared in the same
manner as arrays of primitive variables
• Assuming that a class Student was declared
elsewhere a client application could declare
and allocate an array of 10 students using
Student[ ] students;
students = new Student[10];
Passing Arrays as Arguments
• When an array is passed as an argument to a
method, what is passed is a pointer to the array, not a
new array (arrays are passed by reference)
• This means that if the method makes changes to the
array, these changes are still in effect when the
method returns to its caller
• This is not true for primitive values which are passed
by value and not by reference
• Method header example:
public void read(Student[ ] students) {
Two Dimensional Arrays
• Two dimensional
arrays allows us to
store data that are
recorded in table.
For example:
• Table contains 12
items, we can think
of this as a matrix
consisting of 4 rows
and 3 columns.
Item1
Item2
Item3
Salesgirl #1
10
15
30
Salesgirl #2
14
30
33
Salesgirl #3
200
32
1
Salesgirl #4
10
200
4
Sold
Person
2D arrays manipulations
• Declaration:
– int myArray [ ][ ];
• Creation:
– myArray = new int[4][3]; // OR
– int myArray [ ][ ] = new int[4][3];
• Initialisation:
– Single Value;
• myArray[0][0] = 10;
– Multiple values:
• int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}};
• int tableA[][] = {{10, 15, 30}, {14, 30, 33}};
Variable Size Arrays
• Java treats multidimensional arrays as
“arrays of arrays”. It is possible to
declare a 2D arrays as follows:
– int a[][] = new int [3][];
– a[0]= new int [3];
– a[1]= new int [2];
– a[2]= new int [4];
Try: Write a program to Add two
Matrix
• Define 2 dimensional matrix variables:
– Say: int a[][], b[][];
• Define their size to be 2x3
• Initialise like some values
• Create a matrix c to storage sum value
– c[0][0] = a[0][0] + b[0][0]
• Print the contents of result matrix.
Introduction
•
String manipulation is the most common operation performed in Java
programs. The easiest way to represent a String (a sequence of
characters) is by using an array of characters.
–
–
–
–
–
–
•
•
Example:
char place[] = new char[4];
place[0] = ‘J’;
place[1] = ‘a’;
place[2] = ‘v’;
place[3] = ‘a’;
Although character arrays have the advantage of being able to query
their length, they themselves are too primitive and don’t support a
range of common string operations. For example, copying a string,
searching for specific pattern etc.
Recognising the importance and common usage of String manipulation
in large software projects, Java supports String as one of the
fundamental data type at the language level. Strings related book
keeping operations (e.g., end of string) are handled automatically.
String Operations in Java
• Following are some useful classes
that Java provides for String
operations.
– String Class
– StringBuffer Class
– StringTokenizer Class
String Class
• String class provides many operations
for manipulating strings.
– Constructors
– Utility
– Comparisons
– Conversions
• String objects are read-only (immutable)
Strings Basics
• Declaration and Creation:
String stringName;
stringName = new String (“string value”);
Example:
• String city;
• city = new String (“Bangalore”);
Length of string can be accessed by invoking
length() method defined in String class:
• int len = city.length();
String operations and Arrays
• Java Strings can be concatenated using the +
operator.
– String city = “New” + “York”;
– String city1 = “Delhi”;
– String city2 = “New “+city1;
• Strings Arrays
–
–
–
–
–
String city[] = new String[5];
city[0] = new String(“Melbourne”);
city[1] = new String(“Sydney”);
…
String megacities[] = {“Brisbane”, “Sydney”, “Melbourne”,
“Adelaide”, “Perth”};
String class - Constructors
public String()
Constructs an empty String.
Public String(String value)
Constructs a new string
copying the specified string.
String – Some useful
operations
public int length()
Returns the length of the
string.
public charAt(int index)
Returns the character at the
specified location (index)
public int compareTo( String
Compare the Strings.
anotherString)
public int
compareToIgnoreCase( String
anotherString)
reigonMatch(int start, String
Compares a region of the
other, int ostart, int count)
Strings with the specified start.
String – Some useful
operations
public String replace(char
oldChar, char newChar)
public trim()
public String toLowerCase()
public String toUpperCase()
Returns a new string with all
instances of the oldChar
replaced with newChar.
Trims leading and trailing
white spaces.
Changes as specified.
String Class - example
// StringDemo.java: some operations on strings
class StringDemo {
public static void main(String[] args)
{
String s = new String("Have a nice Day");
// String Length = 15
System.out.println("String Length = " + s.length() );
// Modified String = Have a Good Day
System.out.println("Modified String = " + s.replace('n', 'N'));
// Converted to Uppercse = HAVE A NICE DAY"
System.out.println("Converted to Uppercase = " + s.toUpperCase());
// Converted to Lowercase = have a nice day"
System.out.println("Converted to Lowercase = " + s.toLowerCase());
}
}