Chapter 4. Java Methods Arrays and References
Chapter 4. Java Methods Arrays and References
•Chapter 4
1
Object Oriented Programming Course VKU
Method Definitions
• Methods belong to a class
• Defined inside the class
• Heading
• Return type (e.g. int, float, void)
• Name (e.g. nextInt, println)
• Parameters (e.g. println(…) )
• More…
• Body
• enclosed in braces {}.
• Declarations and/or statements.
Object Oriented Programming Course VKU
Example
• class SpeciesFirstTry
Object Oriented Programming Course VKU
Example, contd.
• class SpeciesFirstTryDemo
Naming Methods
• Use a verb to name methods
• Actions
• getBalance, deposit, changeAddress
• Start a method name with a lowercase letter.
Object Oriented Programming Course VKU
Local Variables
• Declared within a method
• “local to” (confined to) the method definition
• can’t be accessed outside the method
• Not attributes (instance variables)
Object Oriented Programming Course VKU
Pass-By-Value:
Primitive Data Types as Parameters
• When the method is called
• value of each argument is copied (assigned) to its corresponding formal
parameter
• Formal parameters
• initialized to the values passed
• local to their method
• Variables used as arguments cannot be changed by the method
• the method only gets a copy of the variable's value
Object Oriented Programming Course VKU
Arguments to Methods
• An argument in a method invocation can be
• a literal such as 2 or ‘A’
• a variable
• an expression that yields a value
[technically a literal or variable is also an “expression”]
Object Oriented Programming Course VKU
• private
• protected
Object Oriented Programming Course VKU
Method Modifiers
• static
• abstract
• final
• native
• synchronized
• volatile
Object Oriented Programming Course VKU
Class Constructors
• Special method used to initialize member variables of the class
• Same name as the Class name and does not have a return type
• Called when an object is created
• Types:
• Explicit constructors
• Implicit constructors
Object Oriented Programming Course VKU
Arrays in JAVA
Object Oriented Programming Course VKU
Defining an Array
• Define an array as follows:
• variable_name=new <type>[N];
• primes=new int[10];
• Declaring and defining in the same statement:
• int[] primes=new int[10];
• In JAVA, int is of 4 bytes, total space=4*10=40 bytes
Object Oriented Programming Course VKU
Graphical Representation
Index
prime
0 1 2 3 4 5 6 7 8 9
2 1 11 -9 2 1 11 90 101 2
value
Object Oriented Programming Course VKU
What happens if …
• We define
• int[] prime=new long[20];
MorePrimes.java:5: incompatible types
found: long[]
required: int[]
int[] primes = new long[20];
^
• The right hand side defines an array, and thus the array variable
should refer to the same type of array
Object Oriented Programming Course VKU
What happens if …
• We define
• int prime[100];
MorePrimes.java:5: ']' expected
long primes[20];
^
• The C++ style is not permitted in JAVA syntax
Object Oriented Programming Course VKU
What happens if …
• Valid code:
int k=7;
long[] primes = new long[k];
• Invalid Code:
int k;
long[] primes =new long[k];
Compilation Output:
MorePrimes.java:6: variable k might not have been initialized
long[] primes = new long[k];
^
Object Oriented Programming Course VKU
Default Initialization
• When array is created, array elements are initialized
• Numeric values (int, double, etc.) to 0
• Boolean values to false
• Char values to ‘\u0000’ (unicode for blank character)
• Class types to null
Object Oriented Programming Course VKU
Validating Indexes
• JAVA checks whether the index values are valid at runtime
• If index is negative or greater than the size of the array then an
IndexOutOfBoundException will be thrown
• Program will normally be terminated unless handled in the try {} catch {}
Object Oriented Programming Course VKU
What happens if …
Initializing Arrays
• Initialize and specify size of array while declaring an array variable
int[] primes={2,3,5,7,11,13,17}; //7 elements
• You can initialize array with an existing array
int[] even={2,4,6,8,10};
int[] value=even;
• One array but two array variables!
• Both array variables refer to the same array
• Array can be accessed through either variable name
Object Oriented Programming Course VKU
Graphical Representation
even
0 1 2 3 4
2 4 6 8 10
value
Object Oriented Programming Course VKU
Demonstration
long[] primes = new long[20];
primes[0] = 2;
primes[1] = 3;
long[] primes2=primes;
System.out.println(primes2[0]);
primes2[0]=5;
System.out.println(primes[0]);
Object Oriented Programming Course VKU
Output
2
5
Object Oriented Programming Course VKU
Array Length
• Refer to array length using length
• A data member of array object
• array_variable_name.length
• for(int k=0; k<primes.length;k++)
….
• Sample Code:
long[] primes = new long[20];
System.out.println(primes.length);
• Output: 20
Object Oriented Programming Course VKU
Sample Program
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current minimum
for ( int index=0; index < array.length; index++ )
if ( array[ index ] < min )
min = array[ index ] ;
System.out.println("The minimum of this array is: " + min );
}
}
Arrays of Arrays
• Two-Dimensional arrays
• float[][] temperature=new float[10][365];
• 10 arrays each having 365 elements
• First index: specifies array (row)
• Second Index: specifies element in that array (column)
• In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
Object Oriented Programming Course VKU
Graphical Representation
Sample[0] 0 1 2 3 4 5 6 7 8 9
Sample[1] 0 1 2 3 4 5 6 7 8 9
Sample[2] 0 1 2 3 4 5 6 7 8 9
Object Oriented Programming Course VKU
OUTPUT:
20
30
Object Oriented Programming Course VKU
Sample Program
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
// print out the array
for ( int row=0; row < uneven.length; row++ ) //changes row
{
System.out.print("Row " + row + ": ");
for ( int col=0; col < uneven[row].length; col++ ) //changes column
System.out.print( uneven[row][col] + " ");
System.out.println();
}
}
}
Object Oriented Programming Course VKU
Output
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4
Object Oriented Programming Course VKU
Multidimensional Arrays
• A farmer has 10 farms of beans each in 5 countries, and each farm
has 30 fields!
• Three-dimensional array
long[][][] beans=new long[5][10][30];
//beans[country][farm][fields]
Object Oriented Programming Course VKU
What’s a reference
• In Java, reference is a typed named memory space which holds
address of an Object of that type.
• Reference in Java is similar with pointer in C/C++.
• Java is safer, C/C++ is more powerful.
Object Oriented Programming Course VKU
example
• Java:
Class A{…}
A a;
a=new A(); reference
• C/C++:
pointer
struct a{…}
struct a* p = malloc(sizeof(a));
p=&a;
Object Oriented Programming Course VKU
Addition
Object Oriented Programming Course VKU
A swap method?
• Does the following swap method work? Why or why not?
public static void main(String[] args) {
int a = 7;
int b = 35;
// swap a with b?
swap(a, b);
System.out.println(a + " " + b);
}
Value semantics
• value semantics: Behavior where values are copied when assigned, passed as
parameters, or returned.
• All primitive types in Java use value semantics.
• When one variable is assigned to another, its value is copied.
• Modifying the value of one variable does not affect others.
int x = 5;
int y = x; // x = 5, y = 5
y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17
Object Oriented Programming Course VKU
index 0 1 2
a1 value 4
7 15 8 a2
Object Oriented Programming Course VKU
panel1
panel2
Object Oriented Programming Course VKU
Objects as parameters
• When an object is passed as a parameter, the object is not copied. The
parameter refers to the same object.
• If the parameter is modified, it will affect the original object.
Arrays as parameters
• Arrays are also passed as parameters by reference.
• Changes made in the method are also seen by the caller.
public static void main(String[] args) {
int[] iq = {126, 167, 95};
increase(iq); iq
System.out.println(Arrays.toString(iq));
}
public static void increase(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * 2;
}
}
index 0 1 2
• Output:
[252, 334, 190] a value 126
252 167
334 190
95
Object Oriented Programming Course VKU
• Output:
[252, 334, 190]