0% found this document useful (0 votes)
2 views

[6] Programming Language Fundamentals (Part 3)

The document discusses programming language fundamentals, focusing on defining classes, returning objects from methods, and using the 'this' keyword. It covers method overloading, constructor usage, and the organization of classes into packages, along with the importance of javadoc comments for documentation. Additionally, it touches on character and string handling in Java, including methods for string manipulation and counting specific characters.

Uploaded by

denoircaera07
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

[6] Programming Language Fundamentals (Part 3)

The document discusses programming language fundamentals, focusing on defining classes, returning objects from methods, and using the 'this' keyword. It covers method overloading, constructor usage, and the organization of classes into packages, along with the importance of javadoc comments for documentation. Additionally, it touches on character and string handling in Java, including methods for string manipulation and counting specific characters.

Uploaded by

denoircaera07
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

PROGRAMMING

LANGUAGE
FUNDAMENTALS
1
2 DEFINING YOUR OWN
CLASSES (PART 2)
RETURNING AN OBJECT
FROM A METHOD
 As we can return a primitive data value from a
method, we can return an object from a method
also.
 We return an object from a method, we are
actually returning a reference (or an address) of
an object.
− This means we are not returning a copy of an
object, but only the reference of this object

3
SAMPLE OBJECT-RETURNING
METHOD

Here's a sample method that returns an object:

Return
Returntype
typeindicates
indicates
the
the class of anobject
class of an object
we're returning from
we're returning from
the
themethod.
method.
public Fraction simplify( ) {
Fraction simp;
int num = getNumberator();
int denom = getDenominator();
int gcd = gcd(num, denom);
simp = new Fraction(num/gcd, denom/gcd);
return simp;
} Return
Returnan
aninstance
instanceof
of
the Fraction class
the Fraction class
4
A SAMPLE CALL TO simplify
public Fraction simplify( ) {
int num = getNumerator();
f1 = new Fraction(24, 26); int denom = getDenominator();
int gcd = gcd(num, denom);

f2 = f1.simplify(); Fraction simp = new


Fraction(num/gcd,
denom/gcd);
return simp;
}

f1
simp
f2

: Fraction : Fraction

numerator numerator
24 2
denominator denominator
36 3
A SAMPLE CALL TO simplify
(CONT’D) public Fraction simplify( ) {
int num = getNumerator();
f1 = new Fraction(24, 26); int denom = getDenominator();
int gcd = gcd(num, denom);

f2 = f1.simplify(); Fraction simp = new


Fraction(num/gcd,
denom/gcd);
return simp;
}

f1
simp
f2

: Fraction : Fraction

numerator numerator The


Thevalue
valueof ofsimp,
simp,
24 2 which
which is a reference,isis
is a reference,
returned
returnedand andassigned
assigned
denominator denominator to f2.
to f2.
36 3
RESERVED WORD this
 The reserved word this is called a self-
referencing pointer because it refers to an
object from the object's method.
: Object

this

 The reserved word this can be used in three


different ways.

7
THE USE OF this IN THE add
METHOD
public Fraction add(Fraction frac) {

int a, b, c, d;
Fraction sum;

a = this.getNumerator(); //get the receiving


b = this.getDenominator(); //object's num and denom

c = frac.getNumerator(); //get frac's num


d = frac.getDenominator(); //and denom

sum = new Fraction(a*d + b*c, b*d);

return sum;
}
f3 = f1.add(f2)

Because
Because f1 f1 isis
the
the receiving
receiving
object
object (we're
(we're
calling
calling f1's
f1's
method),
method), so so
the
the reserved
reserved
word
word this
this is
is
referring
referring toto f1.
f1.
f3 = f2.add(f1)

This
This time,
time,
we're
we're calling
calling
f2's
f2's method,
method, so so
the
the reserved
reserved
word
word this
this is
is
referring
referring toto f2.
f2.
USING this TO REFER TO
DATA

MEMBERS
In the previous example, we showed the use of
this to call a method of a receiving object.
 It can be used to refer to a data member as
well.

class Person {

int age;

public void setAge(int val) {


this.age = val;
}
. . .
}

11
OVERLOADED METHODS
 Methods can share the same name as long as
− they have a different number of parameters (Rule
1) or
− their parameters are of different data types when
the number of parameters is the same (Rule 2)

public void myMethod(int x, int y) { ... }


public void myMethod(int x) { ... } Rule 1

public void myMethod(double x) { ... }


public void myMethod(int x) { ... } Rule 2
OVERLOADED
CONSTRUCTOR

The same rules apply for overloaded
constructors
− this is how we can define more than one
constructor to a class

public Person( ) { ... }


public Person(int age) { ... } Rule 1

public Pet(int age) { ... }


public Pet(String name) { ... } Rule 2
CONSTRUCTOR AND this
public Fraction( ) {
 To call a //creates 0/1
this(0. 1);
constructor from
}
another
constructor of the public Fraction(int number) {
same class, we //creates number/1
use the reserved this(number, 1);
word this. }

public Fraction(Fraction frac) {


//copy constructor
this(frac.getNumerator(),
frac.getDenominator());
}

public Fraction(int num, int denom) {


setNumerator(num);
setDenominator(denom);
}
CLASS METHODS
 We use the reserved word static to define a
class method.

public static int gcd(int m, int n) {

//the code implementing the Euclidean algorithm


}

public static Fraction min(Fraction f1, Fraction f2) {

//convert to decimals and then compare

}
CALL-BY-VALUE PARAMETER
PASSING
When a method is called,
− the value of the argument is passed to the
matching parameter, and
− separate memory space is allocated to store this
value.
 This way of passing the value of arguments is
called a pass-by-value or call-by-value
scheme.
 Since separate memory space is allocated for
each parameter during the execution of the
method,
− the parameter is local to the method, and therefore
− changes made to the parameter will not affect the
value of the corresponding argument.
CALL-BY-VALUE EXAMPLE
class Tester {
public void myMethod(int one, double two ) {
one = 25;
two = 35.4;
}
}

Tester tester;
int x, y;
tester = new Tester(); 10 20
x = 10; produce
y = 20; s
tester.myMethod(x, y);
System.out.println(x + " " + y);
MEMORY ALLOCATION FOR
PARAMETERS
MEMORY ALLOCATION FOR
PARAMETERS
PARAMETER PASSING: KEY
POINTS
1. Arguments are passed to a method by using the pass-
by- value scheme.
2. Arguments are matched to the parameters from left to
right. The data type of an argument must be
assignment-compatible with the data type of the
matching parameter.
3. The number of arguments in the method call must
match the number of parameters in the method
definition.
4. Parameters and arguments do not have to have the
same name.
5. Local copies, which are distinct from arguments, are
created even if the parameters and arguments share
the same name.
6. Parameters are input to a method, and they are local to
the method. Changes made to the parameters will not
ORGANIZING CLASSES INTO
PACKAGE
For a class A to use class B, their bytecode files
must be located in the same directory.
− This is not practical if we want to reuse
programmer-defined classes in many different
programs.
 The correct way to reuse programmer-defined
classes from many different programs is to
place reusable classes in a package.
 A package is a Java class library.
CREATING A PACKAGE
 The following steps illustrate the process of
creating a package name myutil that includes
the Fraction class.
1. Include the statement
package myutil;
as the first statement of the source file for the
Fraction class.
2. The class declaration must include the visibility
modifier public as
public class Fraction {
...
}
CREATING A PACKAGE
 The following steps illustrate the process of
creating a package name myutil that includes
the Fraction class.
3. Create a folder named myutil, the same name
as the package name. In Java, the package must
have a one-to-one correspondence with the
folder.
4. Place the modified Fraction class into the myutil
folder and compile it.
5. Modify the CLASSPATH environment variable to
include the folder that contains the myutil
folder.
USING javadoc COMMENTS
 Many of the programmer-defined classes we
design are intended to be used by other
programmers.
− It is, therefore, very important to provide
meaningful documentation to the client
programmers so they can understand how to use
our classes correctly.

 By adding javadoc comments to the classes we


design, we can provide a consistent style of
documenting the classes.

 Once the javadoc comments are added to a


class, we can generate HTML files for
documentation by using the javadoc command.
javadoc FOR FRACTION
 This is a portion of
the HTML
documentation for
the Fraction class
shown in a
browser.
 This HTML file is
produced by
processing the
javadoc comments
in the source file
of the Fraction
class.
javadoc TAGS
 The javadoc comments begins with /** and
ends with */.
 Special information such as the authors,
parameters, return values, and others are
indicated by the @ marker
@param
@author
@return
etc
EXAMPLE: javadoc SOURCE
. . .

/**
* Returns the sum of this Fraction
* and the parameter frac. The sum
* returned is NOT simplified.
*
* @param frac the Fraction to add to this this javadoc
* Fraction will produce
*
* @return the sum of this and frac
*/
public Fraction add(Fraction frac) {
...
}
. . .
EXAMPLE: javadoc OUTPUT
29 CHARACTERS AND
STRINGS
CHARACTERS
 In Java, single characters are represented using
the data type char.
 Character constants are written as symbols
enclosed in single quotes.
 Characters are stored in a computer memory
using some form of encoding.
 ASCII, which stands for American Standard
Code for Information Interchange, is one of
the document coding schemes widely used
today.
 Java uses Unicode, which includes ASCII, for
representing char constants.
ASCII ENCODING
9

For
Forexample,
example,
character
character'O'
'O'
isis79 (row
79 (row
70 O value
value7070++
col
colvalue
value99==
79).
79).
UNICODE ENCODING
 The Unicode Worldwide Character
Standard (Unicode) supports the interchange,
processing, and display of the written texts of
diverse languages.
 Java uses the Unicode standard for representing
char constants.
char ch1 = 'X';

System.out.println(ch1);
X
System.out.println( (int) ch1); 88
CHARACTER PROCESSING
char ch1, ch2 = ‘X’; Declaration
Declarationandand
initialization
initialization

System.out.print("ASCII code of character X is " +


(int) 'X' );
Type
Typeconversion
conversion
System.out.print("Character with ASCII code 88 is " between
betweenint
intand
andchar.
char.
+ (char)88 );

This
Thiscomparison
comparison
‘A’ < ‘c’ returns
returnstrue
truebecause
because
ASCII
ASCII value of'A'
value of 'A'isis65
65
while that of 'c' is 99.
while that of 'c' is 99.
STRINGS
 A string is a sequence of characters that is
treated as a single value.
 Instances of the String class are used to
represent strings in Java.
 We can access individual characters of a string
by calling the charAt method of the String
object.
ACCESSING INDIVIDUAL
ELEMENTS

Individual characters in a String accessed with
the charAt method.
String name = "Sumatra";

0 1 2 3 4 5 6
S u m a t r a

name name.charAt( 3 )
The
Themethod
methodreturns
returnsthe
the
This
Thisvariable
variablerefers
refersto
to character
the whole string. character at position##
at position
the whole string. 3.
3.
EXAMPLE: COUNTING
VOWELS
char letter;
System.out.println("Your name:");
String name = scanner.next(); //assume ‘scanner’ is created properly
int numberOfCharacters = name.length();
int vowelCount = 0;
Here’s
Here’sthe
thecode
code
for (int i = 0; i < numberOfCharacters; i++) { to count the
to count the
letter = name.charAt(i); number
numberof ofvowels
vowels
in the input
in the input
if ( letter == 'a' || letter == 'A' || string.
string.
letter == 'e' || letter == 'E' ||
letter == 'i' || letter == 'I' ||
letter == 'o' || letter == 'O' ||
letter == 'u' || letter == 'U'
) {
vowelCount++;
}
}
System.out.print(name + ", your name has " + vowelCount + " vowels");
EXAMPLE: COUNTING ‘Java’
int javaCount = 0;
Continue
Continuereading
readingwords
words
boolean repeat = true; and count how many
and count how many
String word; times
timesthe
theword
wordJava
Java
Scanner scanner = new Scanner(System.in); occurs in the input,
occurs in the input,
ignoring
ignoringthe
thecase.
case.
while ( repeat ) {
System.out.print("Next word:");
word = scanner.next();

if ( word.equals("STOP") ) { Notice
Noticehow
howthe
the
repeat = false; comparison
comparison isdone.
is done.We
We
are not using the ==
are not using the ==
operator.
operator.
} else if ( word.equalsIgnoreCase("Java") ) {
javaCount++;
}
}
OTHER USEFUL STRING
OPERATORS
Method Meaning
compareTo Compares the two strings.
str1.compareTo( str2 )
substring Extracts the a substring from a string.
str1.substring( 1, 4 )
trim Removes the leading and trailing spaces.
str1.trim( )
valueOf Converts a given primitive data value to a string.
String.valueOf( 123.4565 )

startsWith Returns true if a string starts with a specified prefix string.


str1.startsWith( str2 )
endsWith Returns true if a string ends with a specified suffix string.
str1.endsWith( str2 )

• See the String class documentation for details.


PATTERN EXAMPLE
 Suppose students are assigned a three-digit
code:
− The first digit represents the major (5 indicates
Computer Engineering);
− The second digit represents either in-state (1),
out-of-state (2), or foreign (3);
− The third digit indicates campus housing:
 On-campus dorms are numbered 1-7.
 Students
The 3-digit living off-campus
pattern to represent are represented
computer engineering byon-campus
majors living the is
digit 8.
5[123][1-7]

first third
character second character
is 5 character is any digit
is 1, 2, or 3 between 1 and 7
REGULAR EXPRESSIONS
 The pattern is called a regular expression.
 Rules:
− The brackets [ ] represent choices
− The asterisk symbol * means zero or more
occurrences.
− The plus symbol + means one or more
occurrences.
− The hat symbol ^ means negation.
− The hyphen – means ranges.
− The parentheses ( ) and the vertical bar | mean a
range of choices for multiple characters.
REGULAR EXPRESSION
EXAMPLES Description
Expression
[013] A single digit 0, 1, or 3.
[0-9][0-9] Any two-digit number from 00 to 99.
[0-9&&[^4567]] A single digit that is 0, 1, 2, 3, 8, or
9.
[a-z0-9] A single character that is either a
lowercase letter or a digit.
[a-zA-z][a-zA-Z0-9_$]* A valid Java identifier consisting of
alphanumeric characters,
underscores, and dollar signs, with
the first character being an alphabet.
[wb](ad|eed) Matches wad, weed, bad, and beed.
(AZ|CA|CO)[0-9][0-9] Matches AZxx,CAxx, and COxx,
where x is a single digit.
THE replaceAll METHOD
 The replaceAll method replaces all
occurrences of a substring that matches a given
regular expression with a given replacement
string.
Replace all vowels with the symbol @
String originalText, modifiedText;

originalText = ...; //assign string

modifiedText =
originalText.replaceAll("[aeiou]","@");
THE Pattern AND Matcher
CLASSES
 The matches and replaceAll methods of the
String class are shorthand for using the
Pattern and Matcher classes from the
java.util.regex package.
 If str and regex are String objects, then
str.matches(regex);
is equivalent to
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
matcher.matches();
THE compile METHOD
 The compile method of the Pattern class
converts the stated regular expression to an
internal format to carry out the pattern-
matching operation.
 This conversion is carried out every time the
matches method of the String class is
executed, so it is more efficient to use the
compile method when we search for the same
pattern multiple times.
THE find METHOD
 The find method is another powerful method of
the Matcher class.
− It searches for the next sequence in a string that
matches the pattern, and returns true if the
pattern is found.
 When a matcher finds a matching sequence of
characters, we can query the location of the
sequence by using the start and end methods.
THE String CLASS IS
IMMUTABLE
In Java a String object is immutable.
− This means once a String object is created, it
cannot be changed, such as replacing a character
with another character or removing a character
− The String methods we have used so far do not
change the original string. They created a new
string from the original. For example, substring
creates a new string from a given string.
 The String class is defined in this manner for
efficiency reason.
EFFECT OF IMMUTABILITY

We can do this
because String
objects are
immutable.
THE StringBuffer CLASS
 In many string processing applications, we
would like to change the contents of a string. In
other words, we want it to be mutable.
 Manipulating the content of a string, such as
replacing a character, appending a string with
another string, deleting a portion of a string,
and so on, may be accomplished by using the
StringBuffer class.
StringBuffer EXAMPLE
StringBuffer word = new StringBuffer("Java");
word.setCharAt(0, 'D');
word.setCharAt(1, 'i');

word word

Changing a : word.setCharAt(0, 'D'); : StringBuffer


string Java to StringBuffer word.setCharAt(1, 'i');
Diva
Java Diva

Before After
SAMPLE PROCESSING
Replace all vowels in the sentence with ‘X’.
char letter;
String inSentence = JOptionPane.showInputDialog(null, "Sentence:");
StringBuffer tempStringBuffer = new StringBuffer(inSentence);
int numberOfCharacters = tempStringBuffer.length();

for (int index = 0; index < numberOfCharacters; index++) {

letter = tempStringBuffer.charAt(index);

if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E'


||
letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O'
||
letter == 'u' || letter == 'U' ) {
tempStringBuffer.setCharAt(index,'X');
}
}
JOptionPane.showMessageDialog(null, tempStringBuffer );
THE append AND insert
METHODS
We use the append method to append a String
or StringBuffer object to the end of a
StringBuffer object.
− The method can also take an argument of the
primitive data type.
− Any primitive data type argument is converted to
a string before it is appended to a StringBuffer
object.
 We can insert a string at a specified position by
using the insert method.
52 ARRAYS
ARRAY BASICS
 An array is a collection of data values.
 If your program needs to deal with 100
integers, 500 Account objects, 365 real
numbers, etc., you will use an array.
 In Java, an array is an indexed collection of data
values of the same type.
ARRAY OF PRIMITIVE DATA
TYPES
Array Declaration
<data type> [ ] <variable> //variation 1
<data type> <variable>[ ] //variation 2
 Array Creation
<variable> = new <data type> [ <size> ]
 Example
Variation 1 Variation 2
double[ ] rainfall; double rainfall [ ];
rainfall rainfall
= new double[12]; = new double[12];

An array is like an
object!
ACCESSING INDIVIDUAL
ELEMENTS
 Individual elements in an array accessed with
the indexed expression.

double[] rainfall = new double[12];

rainfall
0 1 2 3 4 5 6 7 8 9 10 11

This
Thisindexed
indexed
expression
expressionrefers
refersto
to
The index of the first rainfall[2] the element at
the element at
position
position#2
#2
position in an array is 0.
ARRAY PROCESSING –
SAMPLE 1
Scanner scanner = new Scanner(System.in); The
Thepublic
public
double[] rainfall = new double[12]; constant
constantlength
length
returns the
returns the
capacity
capacityof
ofan
an
double annualAverage, array.
array.
sum = 0.0;

for (int i = 0; i < rainfall.length; i++) {

System.out.print("Rainfall for month " + (i+1));


rainfall[i] = scanner.nextDouble( );
sum += rainfall[i];
}

annualAverage = sum / rainfall.length;


ARRAY PROCESSING –
SAMPLE 2
Scanner scanner = new Scanner(System.in);
double[] rainfall = new double[12];
String[] monthName = new String[12];
The
Thesame
samepattern
pattern
monthName[0] = "January"; for the remaining
for the remaining
monthName[1] = "February"; ten
tenmonths.
months.

double annualAverage, sum = 0.0;

for (int i = 0; i < rainfall.length; i++) {


System.out.print("Rainfall for " + monthName[i] + ": ");
rainfall[i] = scanner.nextDouble();
sum += rainfall[i];
} The
Theactual
actualmonth
month
annualAverage = sum / rainfall.length; name
name insteadof
instead of
aanumber.
number.
ARRAY PROCESSING –
SAMPLE 3
 Compute the average rainfall for each quarter.

//assume rainfall is declared and initialized properly

double[] quarterAverage = new double[4];

for (int i = 0; i < 4; i++) {


sum = 0;
for (int j = 0; j < 3; j++) {
//compute the sum of
sum += rainfall[3*i + j]; //one quarter
}
quarterAverage[i] = sum / 3.0; //Quarter (i+1) average
}
ARRAY INITIALIZATION
 Like other data types, it is possible to declare
and initialize an array at the same time.

int[] number = { 2, 4, 6, 8 };

double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,


9.00, 3.123, 22.084, 18.08 };

String[] monthName = { "January", "February", "March",


"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };

number.length 4
samplingData.length 9
monthName.length 12
VARIABLE-SIZE
DECLARATION
 In Java, we are not limited to fixed-size array
declaration.
 The following code prompts the user for the size
of an array and declares an array of designated
size:
Scanner scanner = new Scanner(System.in);
int size;
int[] number;

System.out.print("Size of an array:"));
size= scanner.nextInt( );

number = new int[size];


ARRAY OF OBJECTS
 In Java, in addition to arrays of primitive data
types, we can declare arrays of objects.
 An array of primitive data is a powerful tool, but
an array of objects is even more powerful.
 The use of an array of objects allows us to
model the application more cleanly and
logically.
THE Person CLASS
 We will use Person objects to illustrate the use
of an array of objects.

Person latte; The


ThePerson
Personclass
class
supports
supports theset
the set
latte = new Person( ); methods and get
methods and get
methods.
methods.
latte.setName("Ms. Latte");
latte.setAge(20);
latte.setGender('F');

System.out.println( "Name: " + latte.getName() );


System.out.println( "Age : " + latte.getAge() );
System.out.println( "Sex : " + latte.getGender() );
CREATING AN OBJECT
ARRAY
Cod
- 1
A
A Person[ ] person;
e person = new Person[20];
Only
Onlythethename
nameperson
person
isisdeclared, no array
declared, no array
person[0] = new Person( ); isisallocated
allocatedyet.
yet.

person

State
of
Memor
y After A
A is executed
CREATING AN OBJECT
ARRAY - 2
Code Person[ ] person;
Now
Nowthe
thearray
storing 20
arrayfor
for
Person
storing 20 Person
B
B person = new Person[20]; objects
objectsisiscreated,
the Person
created,but
objects
but
the Person objects
person[0] = new Person( ); themselves
themselvesare arenot
notyet
yet
created.
created.

perso
n
0 1 2 3 4 16 17 18 19

State
of
Memor
y After B
B is executed
CREATING AN OBJECT
ARRAY - 3
Code Person[ ] person; One
OnePerson
Personobject
objectisis
person = new Person[20]; created
createdand
andthethe
reference
reference to thisobject
to this object
C
C person[0] = new Person( ); isisplaced
placed in position0.
in position 0.

perso
n
0 1 2 3 4 16 17 18 19

State
of Perso
n
Memor
y After C
C is executed
Person ARRAY PROCESSING
– SAMPLE 1
 Create Person objects and set up the person array.

String name, inpStr; int age; char gender;


Scanner scanner = new Scanner(System.in);

for (int i = 0; i < person.length; i++) {


System.out.print(“Enter name:"); name = scanner.next ( );
System.out.print(“Enter age:"); age = scanner.nextInt( );
System.out.print(“Enter gender:"); inpStr = scanner.next( );
gender = inpStr.charAt(0);

person[i] = new Person( ); //create a new Person and assign values

person[i].setName ( name );
person[i].setAge ( age );
person[i].setGender( gender );
}
Person ARRAY PROCESSING
– SAMPLE 2
 Find the youngest and oldest persons.

int minIdx = 0; //index to the youngest person


int maxIdx = 0; //index to the oldest person

for (int i = 1; i < person.length; i++) {

if ( person[i].getAge() < person[minIdx].getAge() ) {


minIdx = i; //found a younger person

} else if (person[i].getAge() > person[maxIdx].getAge() ) {

maxIdx = i; //found an older person


}
}

//person[minIdx] is the youngest and person[maxIdx] is the oldest


OBJECT DELETION –
APPROACH 1 int delIdx = 1;
Delete
DeletePerson
PersonBBby by
A
A person[delIdx] = null; setting
setting the referencein
the reference in
position 1 to null.
position 1 to null.

perso perso
n n
0 1 2 3 0 1 2 3

AA BB CC D
D AA CC D
D

Before A
A is executed After A
A is executed
OBJECT DELETION –
APPROACH 2 int delIdx = 1, last = 3; Delete
DeletePerson
PersonBBbyby
setting
setting the referencein
the reference
A
A person[delIdx] = person[last];
position 1 to the last
position 1 to the last
in

person[last] = null; person.


person.

perso perso
n n
0 1 2 3 0 1 2 3

AA BB CC D
D AA D CC
D

Before A
A is executed After A
A is executed
Person ARRAY PROCESSING
– SAMPLE 3
 Searching for a particular person. (Approach 2
Deletion is used. )
int i = 0;

while ( person[i] != null && !person[i].getName().equals("Latte") ) {


i++;
}

if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");

} else {
//found - successful search
System.out.println("Found Ms. Latte at position " + i);
}
THE for-each LOOP
 This new for loop is available from Java 5.0
 The for-each loop simplifies the processing of
elements in a collection.
 Here we show examples of processing elements
in an array.
int sum = 0; int sum = 0;

for (int i = 0; i < number.length; i++) { for (int value : number) {


sum = sum + number[i]; sum = sum + value;
} }

standard for loop for-each loop


PROCESSING AN ARRAY OF
OBJECTS WITH for-each
Person[] person = new Person[100];
//create person[0] to person[99]

for (int i = 0; i < person.length; i++) {


System.out.println(person[i].getName()); standard for loop
}

for (Person p : person) {


System.out.println(p.getName()); for-each loop
}
for-each: KEY POINTS TO
REMEMBER
 A for-each loop supports read access only. The
elements cannot be changed.
 A single for-each loop allows access to a single
array only, i.e., you cannot access multiple
arrays with a single for-each loop.
 A for-each loop iterates over every element of a
collection from the first to the last element. You
cannot skip elements or iterate backward.
PASSING ARRAYS TO
METHODS - 1
Code A
A public int searchMinimum(float[] number))
{
minOne

= searchMinimum(arrayOne);

At A
A before searchMinimum
arrayOne A.
A. Local
Local
variable
variablenumber
number
does
does not exist
not exist
before the
before the
method
method
execution
execution
State
of
Memor
PASSING ARRAYS TO
METHODS - 2
Code public int searchMinimum(float[] number))
{
minOne
B
B

= searchMinimum(arrayOne);

The address is copied B


at
B
arrayOne numbe
B.
B. The
Thevalue
valueof
ofthe
r argument,
the
argument,which
whichisis
an
anaddress,
address,isiscopied
copied
to the parameter.
to the parameter.
State
of
Memor
PASSING ARRAYS TO
METHODS - 3
Code public int searchMinimum(float[] number))
{
minOne

= searchMinimum(arrayOne);
C
C
}

While at C
C inside the method

arrayOne numbe C.
C. The
Thearray
array
r isis accessed
accessed
via
vianumber
number
inside
insidethe
the
method.
method.
State
of
Memor
PASSING ARRAYS TO
METHODS - 4
Code public int searchMinimum(float[] number))
{
minOne

= searchMinimum(arrayOne);

D
D }

At D
D after searchMinimum
arrayOne numbe
D.
D. The
Theparameter
parameterisis
r erased.
erased.The
The
argument
argumentstill
stillpoints
points
to the same object.
to the same object.
State
of
Memor
TWO-DIMENSIONAL ARRAYS
 Two-dimensional arrays are useful in representing
tabular information.
DECLARING AND CREATING
A 2-D
Declaration
ARRAY
<data type> [][] <variable> //variation 1
<data type> <variable>[][] //variation 2

Creation
<variable> = new <data type> [ <size1> ][ <size2> ]

Example
payScaleTable
0 1 2 3 4
0
double[][] payScaleTable;
payScaleTable 1
= new double[4][5]; 2
3
ACCESSING AN ELEMENT
 An element in a two-dimensional array is accessed
by its row and column index.
SAMPLE 2-D ARRAY
PROCESSING
 Find the average of each row.

double[ ] average = { 0.0, 0.0, 0.0, 0.0 };

for (int i = 0; i < payScaleTable.length; i++) {

for (int j = 0; j < payScaleTable[i].length; j++) {

average[i] += payScaleTable[i][j];
}

average[i] = average[i] / payScaleTable[i].length;


}
JAVA IMPLEMENTATION OF
2-D ARRAYS
 The sample array creation

payScaleTable = new double[4][5];


is really a shorthand for
payScaleTable = new double [4][ ];

payScaleTable[0] = new double [5];


payScaleTable[1] = new double [5];
payScaleTable[2] = new double [5];
payScaleTable[3] = new double [5];
TWO-DIMENSIONAL ARRAYS
 Subarrays may be different lengths.
 Executing
triangularArray = new double[4][ ];
for (int i = 0; i < 4; i++)
triangularArray[i] = new double [i + 1];
results in an array that looks like:

You might also like