You are on page 1of 23

Types in Java

• 8 Primitive Types
– byte, short, int, long
– float, double
– boolean
– Char
• Also some Object types: e.g. “String”

• But only single items. What if we want to


store lots of items – e.g. midsem marks?
Arrays

• Arrays are data structures that can hold a


series of values
– An array uses an index to access a particular
value
Primitive Type Syntax

double number = 3;
Array Syntax

double[ ] number;
Array Syntax

double[ ] number = {1,2,3} ;


String s[ ] = {"This", "is", "an", "array"};
Array Syntax

double[ ] number;

Can also initialize with the “new” construct:

double [ ] number = new double[3];


Array Implementation
Every time an array is initialized, using new,
or by {… },
• a contiguous block of memory is assigned
for it
• the array name (the identifier number) is
assigned the start address (In Java, this
address is the reference for this variable).
• number[3] gets an address 3 shifted from
the start
Parallel Arrays
• int[ ] rollNum= {6016, 6024, 6078};
• double[ ] midsemMarks
= {61.7, 54 , 74.2 };
• String[ ] name = {"AbhishekA", "AbhishekS",
"Ankit"};

• In practice, parallel arrays are hard to maintain.


• Better is to define an object with data: rollNum,
marks, and name, and define arrays of these
objects
Printing an Array
• class ArrayPrint
• {
• public static void main (String arg[])
• {
• double numbers[] = {1,2,3};
• double numbers2[] = {1,2,3,4};
• String s[] = {"This", "is", "an", "array"};
• printArray (s,4);
• }

• public static void printArray (String[] arr, int


length)
• { for(int j=0;j<length;j++)
• System.out.println("Element "+j+"=
"+arr[j]);
• }
• }
Array Length
Array objects have some predefined variables
e.g. length

String s[ ] = {"This", "is", "an", "array"};


System.out.println("Length of s: "+
s.length);

Dot Syntax: If x is an object, then x.y tells


you that y is some property computed for
the object x.
Finding the average
class Average {
public static void main (String arg[])
{
float dailyRainFall[] = {12.3, 13.5, 4.2, 2.4, 1.1, 0, 10.8};
int i;

float average = 0;
for (i=0; i<7; i++)
{ average += dailyRainFall[i]; }
average /= 7;
System.out.println (“Average rain fall: ” + average + “
mm”);
}
}
Finding the average
for (i=0; i<7; i++)
{ average += dailyRainFall[i]; }
average /= 7;

Everytime I have another day of rain, I need to


change the number “7” in my program

Instead, I can use

for (i=0; i<dailyRainFall.length; i++)


{ average += dailyRainFall[i]; }
average /= dailyRainFall.length;
class ArrayPrint
class ArrayPrint
{
public static void main (String arg[])
{
String s[ ] = {"This", "is", "a", "test", "array"};
printArray(s);
System.out.println( "s[0] length is: "+s[0].length() );
}

public static void printArray (String[] arr)


{ for(int j=0;j<arr.length;j++)
System.out.println("Element "+j+"= "+arr[j]);
}

// exercise: define lengthOfStringArray (String[] s)


}
Finding maximum
class Maximum {
public static void main (String arg[]) {
int n = 100;
double numbers[] = new double[n];

Initialize (numbers, n);


System.out.println (“Maximum: ” +
FindMax (numbers, n));
}
Finding maximum
public static void Initialize (double
numbers[], int length) {
int i;
for (i=0; i<length; i++) {
numbers[i] = Math.sin(2*Math.PI/(i+1))
+ Math.cos(2*Math.PI/(i+2));
}
}
Finding maximum
public static double FindMax (double numbers[],
int length) {
double max = numbers[0];
int i;

for (i=1; i<length; i++) {


if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
} // end class
Methods to return more than
one parameter
• Want to identify both maximum marks, and
also who has this maximum marks
– Need to return two values from FindMax
– Use a 2-element array as return type
Finding max and max index
class Maximum {
public static void main (String arg[]) {
int n = 100;
double numbers[] = new double[n];
double result[];

Initialize (numbers, n);


result = FindMax (numbers, n);
System.out.println ("Maximum: " + result[0]
+ ", Position: " + (int)result[1]);
}
Finding max and max index
public static void Initialize (double
numbers[], int length) {
int i;
for (i=0; i<length; i++) {
numbers[i] = Math.sin(2*Math.PI/(i+1)) +
Math.cos(2*Math.PI/(i+2));
}
}
Finding max and max index
public static double[] FindMax (double numbers[],
int length) {
double result[] = {numbers[0], 0};
int i;

for (i=1; i<length; i++) {


if (numbers[i] > result[0]) {
result[0] = numbers[i];
result[1] = i;
}
}
return result;
}
} // end class
Array Variables

• Array variables are typed by their array


declaration

• Is this legal?

int[] rollNum= {6016, 6024, 6078};


int[] a = {1,2,3,4};
a = rollNum;

• Now the part of memory previously accessed


through “a” is lost. “a” and “rollNum” now point to
the same place in memory.
Passing Arrays
• The method findAverage() is defined thus:
public static double findAverage (double[] arr)
{ for (int i = 1; i<arr.length; i++)
{ arr[0] += arr[i]; }
return (arr[0] / arr.length) ; // will this work?
}

• Q. I invoke this method on the array numbers[ ].


findAverage(numbers). Does numbers[0] remain what it
was or does it change?

• Since method arguments in Java are passed by reference


– so numbers[0] has the same address as arr[0] inside the
method; and modifications to arrays inside the method
are reflected outside the method
class ArrayMidsems
class ArrayMidsems
{
/* gets the marks of i-th student */
public static void main (String arg[])
public static double getMarks (double[] marks, int i)
{
{ if (i > marks.length-1)
int[] rollNum= {6016, 6024, 6078};
{ System.out.println ("Array index out of bounds");
double[] midsemMarks = {61.7, 54 , 74.2 };
return -999;
String[] name = {"Abhishek A", "Abhishek S", "Ankit"};
}
System.out.println (getMarks(rollNum, midsemMarks, 6024));
return marks[i];
}
}
public static void printArray (String[] arr, int length)
/* returns the marks for student with target rollNum */
{ for(int j=0;j<length;j++)
public static double getMarks (int[] n, double[] marks, int target)
System.out.println("Element "+j+"= "+arr[j]);
{ if (n.length !=marks.length)
}
{ System.out.println ("Array lengths don't match!");
return -999;
public static double findMax (double numbers[])
}
{ double max = numbers[0];
for (int j=0; j< n.length; j++)
for (int i=1; i<numbers.length; i++)
{ if (n[j] == target) return marks[j]; }
{ if (numbers[i] > max)
return -999;
max = numbers[i];
}
}
} // end ArrayMidsems
return max;
}

public static double findAverage (double[] arr)


{
double sum = 0;
for (int i = 0; i<arr.length; i++)
{ sum += arr[i];
}
return (sum / arr.length) ;
}

You might also like