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

oop-java-unit-iv-batu-prp-

This document covers Unit IV of Object-Oriented Programming using Java, focusing on arrays, including their declaration, creation, and manipulation, as well as multidimensional arrays and variable-length argument lists. It includes case studies such as card shuffling and a GradeBook class that utilizes arrays for storing grades. Additionally, it discusses passing arrays to methods and using command-line arguments in Java applications.

Uploaded by

mahajangaurav497
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

oop-java-unit-iv-batu-prp-

This document covers Unit IV of Object-Oriented Programming using Java, focusing on arrays, including their declaration, creation, and manipulation, as well as multidimensional arrays and variable-length argument lists. It includes case studies such as card shuffling and a GradeBook class that utilizes arrays for storing grades. Additionally, it discusses passing arrays to methods and using command-line arguments in Java applications.

Uploaded by

mahajangaurav497
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

BT-COE404

Object-Oriented Programming using


Java
UNIT-IV
• Array: Introduction, Declaring and Creating Arrays, Examples Using Arrays,
Case Study: Card Shuffling and Dealing Simulation, Enhanced for Statement,
Passing Arrays to Methods, CaseStudy: Class GradeBook Using an Array to
Store Grades,
• Multidimensional Arrays, Case Study: Class GradeBook Using a Two-
Dimensional Array, Variable-Length Argument Lists, Using Command-Line
Arguments, Class Arrays.

By:Prof.Pankaj R. Patil
Introduction

• Arrays
– Data structures
– Related data items of same type
– Remain same size once created
• Static entries

 2002 Prentice Hall. All rights reserved.


Arrays

• Array
– Group of contiguous memory locations
• Each memory location has same name
• Each memory location has same type
- The elements of an array can be either primitive types or reference
types
- we specify the name of the reference to the array and the position
number of the element in the array.
- The position number of the element is called the element’s index or
subscript.
 2002 Prentice Hall. All rights reserved.
Name of array (Note c[ 0 ] -45
that all elements of c[ 1 ] 6
this array have the
same name, c) c[ 2 ] 0
c[ 3 ] 72
c[ 4 ] 1543
c[ 5 ] -89
c[ 6 ] 0
c[ 7 ] 62

c[ 8 ] -3

Position number (index c[ 9 ] 1


of subscript) of the 6453
c[ 10 ]
element within array c
c[ 11 ] 78

Fig. 7.1 A 12-element array.

 2002 Prentice Hall. All rights reserved.


Arrays (cont.)

• Subscript
– Also called an index
– Position number in square brackets
– Must be integer or integer expression

a = 5;
b = 6;
c[ a + b ] += 2;

• Adds 2 to c[ 11 ]
• Subscripted array name is an lvalue
 2002 Prentice Hall. All rights reserved.
Arrays (cont.)

• Examine array c
– c is the array name
– c.length accesses array c’s length
– c has 12 elements ( c[0], c[1], … c[11] )
• The value of c[0] is –45
• The brackets ([]) are in highest level of precedence in
Java

 2002 Prentice Hall. All rights reserved.


Opera tors Associa tivity Type
() [] . left to right highest
++ -- right to left unary postfix
++ -- + - ! (type) right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
& left to right boolean logical AND
^ left to right boolean logical exclusive OR
| left to right boolean logical inclusive OR
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 7.2 Precedence a nd a ssocia tivity of the opera tors
discussed so fa r.

 2002 Prentice Hall. All rights reserved.


Declaring and Allocating Arrays

• Declaring and Allocating arrays


– Arrays are objects that occupy memory
– Allocated dynamically with operator new
int c[] = new int[ 12 ];
– Equivalent to
int c[]; // declare array
c = new int[ 12 ]; // allocate array
• We can allocate arrays of objects too
String b[] = new String[ 100 ];

 2002 Prentice Hall. All rights reserved.


Examples Using Arrays

• Declaring arrays
-When an array is declared, the type of the array and the square brackets can be combined at the
beginning of the declaration to indicate that all the identifiers in the declaration are array variables.
For example, the declaration
double[] array1, array2;
- indicates that array1 and array2 are each “array of double” variables. The preceding declaration is
equivalent to:
double array1[];
double array2[];
or
double[] array1;
double[] array2;

 2002 Prentice Hall. All rights reserved.


 2002 Prentice Hall. All rights reserved.
• Initializing arrays
- A program can create an array and initialize its elements with an array initializer, which is a
comma-separated list of expressions (called an initializer list) enclosed in braces ({ and });
- the array length is determined by the number of elements in the initializer list. For
example, the declaration
int n[] = { 10, 20, 30, 40, 50 };

-creates a five-element array with index values 0, 1, 2, 3 and 4. Element n[ 0 ] is initialized to


10, n[ 1 ] is initialized to 20, and so on.
- This declaration does not require new to create the array object.
• Calculating the Values to Store in an Array
- Constant variables (also known as final variables) must be initialized before they are used
and cannot be modified thereafter. If you attempt to modify a final variable after it is
initialized in its declaration (as in line 8), the compiler issues the error message cannot
assign a value to final variable
 2002 Prentice Hall. All rights reserved.
 2002 Prentice Hall. All rights reserved.
 2002 Prentice Hall. All rights reserved.
 2002 Prentice Hall. All rights reserved.
Case Study: Card Shuffling and Dealing Simulation
• We first develop class Card (Fig. 7.9), which represents a playing
card that has a face (e.g., "Ace", "Deuce", "Three", …, "Jack",
"Queen", "King") and a suit (e.g., "Hearts", "Diamonds", "Clubs",
"Spades").
• Next, we develop the DeckOfCards class (Fig. 7.10), which creates a
deck of 52 playing cards in which each element is a Card object. We
then build a test application (Fig. 7.11) that demonstrates class
DeckOfCards’s card shuffling and dealing capabilities.

By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
Enhanced for Statement
• iterates through the elements of an array or a collection without using a counter (thus
avoiding the possibility of “stepping outside” the array).
• The syntax of an enhanced for statement is:
for ( parameter : arrayName )
statement
• where parameter has two parts—a type and an identifier (e.g., int number)—and
arrayName is the array through which to iterate.
• Figure 7.12 uses the enhanced for statement (lines 12–13) to sum the integers in an array of
student grades. The type specified in the parameter to the enhanced for is int, because
array contains int values—the loop selects one int value from the array during each
iteration. The enhanced for statement iterates through successive values in the array one by
one. The enhanced for header can be read as “for each iteration, assign the next element
of array to int variable number, then execute the following statement.”

By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
• Lines 12–13 are equivalent to the following counter-controlled
repetition used in lines 12–13 of Fig. 7.5 to total
the integers in array:
for ( int counter = 0; counter < array.length; counter++ )
total += array[ counter ];
• enhanced for statement can be used only to obtain array elements—
it cannot be used to modify elements. If your program needs to
modify elements, use the traditional counter-controlled for
statement.

By:Prof.Pankaj R. Patil
Passing Arrays to Methods

• To pass array argument to a method


– Specify array name without brackets
• Array hourlyTemperatures is declared as
int hourlyTemperatures = new int[ 24 ];

• The method call


modifyArray( hourlyTemperatures );

• Passes array hourlyTemperatures to method modifyArray

 2002 Prentice Hall. All rights reserved.


By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
Case Study: Class GradeBook Using an Array to
Store Grades
• The version of class GradeBook (Fig. 7.14) presented here uses an array of integers to store
the grades of several students on a single exam.
• This eliminates the need to repeatedly input the same set of grades. Array grades is
declared as an instance variable in line 7— therefore, each GradeBook object maintains its
own set of grades.
• The class’s constructor (lines 10–14) has two parameters—the name of the course and an
array of grades. When an application (e.g., class GradeBookTest in Fig. 7.15) creates a
GradeBook object, the application passes an existing int array to the constructor, which
assigns the array’s reference to instance variable grades (line 13).
• The size of the array grades is determined by the class that passes the array to the
constructor. Thus, a GradeBook object can process a variable number of grades.
• Once the grades are stored in instance variable grades of class GradeBook, all the class’s
methods can access the elements of grades as often as needed to perform various
calculations.
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
Multidimensional Arrays (Multiple-Subscripted Arrays)
• Multidimensional arrays with two dimensions are often used to represent
tables of values consisting of information arranged in rows and columns.
• To identify a particular table element, we must specify two indices. By
convention, the first identifies the element’s row and the second its column.
Arrays that require two indices to identify a particular element are called two-
dimensional arrays. (Multidimensional arrays can have more than two
dimensions.)
• Java does not support multidimensional arrays directly, but it does allow the
programmer to specify one-dimensional arrays whose elements are also one-
dimensional arrays, thus achieving the same effect.
• an array with m rows and n columns is called an m-by-n array.

 2002 Prentice Hall. All rights reserved.


Multidimensional Arrays (Multiple-Subscripted Arrays)
• Multiple-subscripted arrays
– Tables with rows and columns
• Double-subscripted (two-dimensional) array
• Declaring double-subscripted array b[2][2]
int b[][] = { { 1, 2 }, { 3, 4 } };
– 1 and 2 initialize b[0][0] and b[0][1]
– 3 and 4 initialize b[1][0] and b[1][1]
int b[][] = { { 1, 2 }, { 3, 4, 5 } };
– row 0 contains elements 1 and 2
– row 1 contains elements 3, 4 and 5

 2002 Prentice Hall. All rights reserved.


Multiple-Subscripted Arrays (cont.)

• Allocating multiple-subscripted arrays


– Can be allocated dynamically
• 3-by-4 array
int b[][];
b = new int[ 3 ][ 4 ];
• Rows can have different number of columns
int b[][];
b = new int[ 2 ][ ]; // Create rows
b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0
b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1

 2002 Prentice Hall. All rights reserved.


Column 0 Column 1 Column 2 Column 3

Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]

Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript (or index)

Row Subscript (or index)

Array name

Fig. 7.14 A double-subscripted array with three rows and four columns.

 2002 Prentice Hall. All rights reserved.


By:Prof.Pankaj R. Patil
Two-Dimensional Array Example: Displaying Element Values

By:Prof.Pankaj R. Patil
Case Study: Class GradeBook Using a Two- Dimensional Array
Storing Student Grades in a Two-Dimensional Array in Class GradeBook

By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
Variable-Length Argument Lists
• With variable-length argument lists, you can create methods that receive an
unspecified number of arguments.
• An argument type followed by an ellipsis (...) in a method’s parameter list
indicates that the method receives a variable number of arguments of that
particular type.
• This use of the ellipsis can occur only once in a parameter list, and the ellipsis,
together with its type, must be placed at the end of the parameter list.
• Figure 7.20 demonstrates method average (lines 7–16), which receives a
variable length sequence of doubles. Java treats the variable-length argument
list as an array whose elements are all of the same type. Hence, the method
body can manipulate the parameter numbers as an array of doubles.
• Method average has a variable-length argument list (line 7), so it can average
as many double arguments as the caller passes. The output shows that each
call to method average returns theBy:Prof.Pankaj
correct value.
R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
Using Command-Line Arguments
• On many systems it is possible to pass arguments from the command line (these are known
as command-line arguments) to an application by including a parameter of type String[]
(i.e., an array of Strings) in the parameter list of main, exactly as we have done in every
application in the book.
• By convention, this parameter is named args.
• When an application is executed using the java command, Java passes the command-line
arguments that appear after the class name in the java command to the application’s main
method as Strings in the array args.
• The number of arguments passed in from the command line is obtained by accessing the
array’s length attribute. For example, the command "java MyClass a b" passes two
command-line arguments, a and b, to application MyClass. Note that command-line
arguments are separated by white space, not commas.
• When this command executes, MyClass’s main method receives the two-element array args
(i.e., args.length is 2) in which args[ 0 ] contains the String "a" and args[ 1 ] contains the
String "b". Common uses of command-line arguments include passing options and file
names to applications.
By:Prof.Pankaj R. Patil
• Figure 7.21 uses three command-line arguments to initialize an array.
• When the program executes, if args.length is not 3, the program
prints an error message and terminates (lines 9–12). Otherwise, lines
14–32 initialize and display the array based on the values of the
command-line arguments.
• The command-line arguments become available to main as Strings in
args.
• Line 16 gets args[ 0 ]—a String that specifies the array size—and
converts it to an int value that the program uses to create the array
in line 17.
• The static method parseInt of class Integer converts its String
argument to an int.
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil
By:Prof.Pankaj R. Patil

You might also like