SlideShare una empresa de Scribd logo
1 de 45
ARRAYS IN JAVA
Ashish K. Nayyar
WHAT ARE ARRAYS?
It is a user defined homogeneous datatype. Unlike
a variable used to store a single value,
int debt =2;
an array declared is used to store series
of values of the same type(homogeneous),
sequentially.
int marks[]=new int[5];
2
debt
s
DECLARING AN ARRAY VARIABLE
Array in java is created in two steps.
In first step we just create a reference name
int [ ] marks;
int marks[ ];
Both syntaxes are equivalent. No memory allocation
at this point.
To create actual array we use new operator as shown
below:
marks=new int[5];
OR
We can also create array in single step as:
int marks[]=new int[5];
INITIALIZATION OF AN ARRAY
While initializing an array new operator is not required
int[ ] marks={72,61,81,79,72};
In JAVA, int is of 4 bytes, total space=4*5=20 bytes
GRAPHICAL REPRESENTATION
marks[0] marks[1] marks[2] marks[3] marks[4]
72 61 81 79 72
marks
Index
value
WHAT HAPPENS IF …
If we define
int[ ] marks=new long[5];
marks.java:5: incompatible types
found: long[ ]
required: int[ ]
int[ ] marks = new int[5];
^
The right hand side defines an array, and thus
the array variable should refer to the same
type of array
WHAT HAPPENS IF …
 Valid code:
int k=5;
int[ ] marks = new int[k];
 Invalid Code:
int k;
int[ ] marks =new int[k];
Compilation Output:
More marks.java:6: variable k might not have been initialized
int[ ] marks = new int[k];
^
ARRAY SIZE THROUGH INPUT
….
BufferedReader in1 = new BufferedReader (new InputStreamReader(System.in));
int num;
System.out.println("Enter a Size for Array:");
num = Integer.parseInt(in1.readLine( );
int [ ] marks = new int[num];
System.out.println(“Array Length=”+marks.length);
….
SAMPLE RUN:
Enter a Size for Array:
4
Array Length=4
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
ACCESSING ARRAY ELEMENTS
 Index of an array is defined as
 Positive int, byte or short values
 Expression that results into these types
 Any other types used for index will give error
 long, double, etc.
 Indexing starts from 0 and ends at N-1
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 ArrayIndexOutOfBoundException will be thrown
 Program will normally be terminated unless handled in
the try {} catch {}
WHAT HAPPENS IF …
int[] marks = new int[5];
marks[6]=33;
….
Runtime Error:
Exception in thread “main”
java.lang.ArrayIndexOutOfBoundsException: 6
at marks.main(marks.java:6)
REUSING ARRAY VARIABLES
 Array variable is separate from array itself
 Like a variable can refer to different values at
different points in the program
 Use array variables to access different arrays
int[] marks=new int[5];
……
marks=new int[50];
 Previous array will be discarded
 Cannot alter the type of array
INITIALIZING ARRAYS
 Initialize and specify size of array while
declaring an array variable
int[] marks={2,3,5,7,11,13,17}; //7 elements
 You can initialize array with an existing array
int[] even={72,74,66,68,70};
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
GRAPHICAL REPRESENTATION
0 1 2 3 4
72 74 66 68 70
even
value
DEMONSTRATION
int[] marks = new int[20];
marks[0] = 2;
marks[1] = 3;
int[] marks2=marks;
System.out.println(marks2[0]);
marks2[0]=5;
System.out.println(marks[0]);
OUTPUT
2
5
ARRAY LENGTH
 Refer to array length using length
 A data member of array object
 array_variable_name.length
 for(int k=0; k<marks.length;k++)
….
 Sample Code:
int[] marks = new int[5];
System.out.println(marks.length);
Output: 5
CHANGE IN ARRAY LENGTH
 If number of elements in the array are changed,
JAVA will automatically change the length attribute!
Changing the size of array is not
possible!
On changing the size of an existing array, a new array gets
created at a different memory location.
import java.io.*;
class Array1{
public static void main(String args[])throws IOException
{
int n,i,noe;
BufferedReader in1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no of array elements");
noe=Integer.parseInt(in1.readLine());
int arr[]=new int[noe];
System.out.println("Array details"+arr);
System.out.println("Enter "+ noe+" array elements");
for(i=0;i<arr.length;i++)
{
arr[i]=Integer.parseInt(in1.readLine());
}
System.out.println("Entered array elements are as follows:");
for(i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
System.out.println("nLets increase number of elements by 2 ");
arr=new int[noe+2];
System.out.println("Array details after increased size"+arr);
System.out.println("Enter "+ (noe+2)+" array elements");
for(i=0;i<arr.length;i++)
{
arr[i]=Integer.parseInt(in1.readLine());
}
System.out.println("Entered array elements are as follows:");
for(i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
}
}
Different memory
address
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
INITIALIZING ARRAY OF ARRAYS
int[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72,
88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93},
{93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98,
78, 56, 99} };
//7 arrays with 5 elements each
ARRAYS OF ARRAYS OF VARYING LENGTH
(JAGGED ARRAYS)
 All arrays do not have to be of the same length
float[][] samples;
samples=new float[5][];//defines no of rows in an array
samples[0]=new float[6];
samples[1]=new float[101];
 Not required to define all arrays
INITIALIZING VARYING SIZE ARRAYS
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
To allocate memory for a 2D array, we need to specify the
memory for the first(Leftmost) dimension. Then remaining
dimensions can be allocated separately.
For eg:
int arr2d[][]=new int[3][];
arr2d[0]=new int[3];
arr2d[1]=new int[3];
arr2d[2]=new int[3];
Above declaration allocates memory for the first dimension of
arr2d when it is declared. Then we allocate memory for the
second dimension separately. There is no benefit of doing
memory allocation this way in above example but it is helpful
when we may want to allocate unequal number of elements
across each row. An array created in this fashion in java is called
Jagged Array.
JAGGED ARRAY
Class JaggedArray {
public static void main(String args[])
{
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
{ for(j=0; j<i+1; j++)
{
twoD[i][j] = k;
k++;
}
}
for(i=0; i<4; i++)
{
for(j=0; j<i+1; j++)
{
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
Output:
0
1 2
3 4 5
6 7 8 9
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();
}
}
}
OUTPUT
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4
TRIANGULAR ARRAY OF ARRAYS
 Triangular Array
for(int k=0; k<samples.length;k++)
samples[k]=new float[k+1];
MULTIDIMENSIONAL ARRAYS
 A farmer has 10 farms of beans each in 5 countries,
and each farm has 30 fields!
 Three-dimensional array
int[][][] beans=new int[5][10][30];
//beans[country][farm][fields]
VARYING LENGTH IN MULTIDIMENSIONAL
ARRAYS
 Same features apply to multi-dimensional arrays as
those of 2 dimensional arrays
int beans=new int[3][][];//3 countries
beans[0]=new int[4][];//First country has 4 farms
beans[0][4]=new int[10];
//Each farm in first country has 10 fields
Vector
Vector is a legacy class available in java.util package. Vector
implements a dynamic array. Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
The first form creates a default vector, which has an initial size of
10.
The second form creates a vector whose initial capacity is specified
by size.
The third form creates a vector whose initial capacity is specified
by size and whose increment is specified by incr. The increment
specifies the number of elements to allocate each time that a vector
is resized upward.
Important Points:
1. All vectors start with an initial capacity.
2. After this initial capacity is reached, the next time that you
attempt to store an object in the vector, the vector
automatically allocates space for that object plus extra room
for additional objects.
3. By allocating more than just the required memory, the vector
reduces the number of allocations that must take place. This
reduction is important, because allocations are costly in terms
of time.
4. The amount of extra space allocated during each reallocation
is determined by the increment that you specify when you
create the vector.
5. If you don’t specify an increment, the vector’s size is doubled
by each allocation cycle.
Vector defines these protected data members:
int capacityIncrement;
int elementCount;
The increment value is stored in capacityIncrement. The number of elements
currently in the vector is stored in elementCount.
Vector defines several legacy methods,
1.void addElement(Object element): The object specified by element is added
to the vector.
2. int capacity( ): Returns the capacity of the vector.
3. boolean contains(Object element): Returns true if element is
contained by the vector, and returns false if it is not.
4. Object elementAt(int index): Returns the element at the
location specified by index.
5. void ensureCapacity(int size) :Sets the minimum capacity of the
vector to size.
6. Object firstElement( ): Returns the first element in the vector.
7. int indexOf(Object element) :Returns the index of the first
occurrence of element. If the object is not in the vector, –1 is
returned.
8. int indexOf(Object element, int start) Returns the index of
the first occurrence of element at or after start. If the object is not
in that portion of the vector -1 is returned.
9. void insertElementAt(Object element, int index): Adds
element to the vector at the location specified by index.
10. boolean isEmpty( ): Returns true if the vector is empty
and returns false if it contains one or more elements.
11. void removeAllElements( ): Empties the vector. After this
method executes, the size of the vector is zero.
12. boolean removeElement(Object element): Removes element from the vector.
If more than one instance of the specified object exists in the vector, then it is the
first one that is removed. Returns true if successful and false if the object is not
found.
13. void removeElementAt(int index): Removes the element at the
location specified by index.
14. void setElementAt(Object element, int index):The location specified by
index is assigned element.
15. void setSize(int size): Sets the number of elements in the vector to size. If the
new size is less than the old size, elements are lost. If the new size is larger than the
old size, null elements are added.
// Demonstrate various Vector operations.
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after 4 additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +(Integer)v.firstElement());
System.out.println("Last element: " +(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
The output from this program is shown here:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12

Más contenido relacionado

Similar a javaArrays.pptx

Similar a javaArrays.pptx (20)

Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Array
ArrayArray
Array
 
Arrays In General
Arrays In GeneralArrays In General
Arrays In General
 
Array in C full basic explanation
Array in C full basic explanationArray in C full basic explanation
Array in C full basic explanation
 
Core java day2
Core java day2Core java day2
Core java day2
 
Array
ArrayArray
Array
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 

Último

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Último (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

javaArrays.pptx

  • 2. WHAT ARE ARRAYS? It is a user defined homogeneous datatype. Unlike a variable used to store a single value, int debt =2; an array declared is used to store series of values of the same type(homogeneous), sequentially. int marks[]=new int[5]; 2 debt s
  • 3. DECLARING AN ARRAY VARIABLE Array in java is created in two steps. In first step we just create a reference name int [ ] marks; int marks[ ]; Both syntaxes are equivalent. No memory allocation at this point. To create actual array we use new operator as shown below: marks=new int[5]; OR We can also create array in single step as: int marks[]=new int[5];
  • 4. INITIALIZATION OF AN ARRAY While initializing an array new operator is not required int[ ] marks={72,61,81,79,72}; In JAVA, int is of 4 bytes, total space=4*5=20 bytes
  • 5. GRAPHICAL REPRESENTATION marks[0] marks[1] marks[2] marks[3] marks[4] 72 61 81 79 72 marks Index value
  • 6. WHAT HAPPENS IF … If we define int[ ] marks=new long[5]; marks.java:5: incompatible types found: long[ ] required: int[ ] int[ ] marks = new int[5]; ^ The right hand side defines an array, and thus the array variable should refer to the same type of array
  • 7. WHAT HAPPENS IF …  Valid code: int k=5; int[ ] marks = new int[k];  Invalid Code: int k; int[ ] marks =new int[k]; Compilation Output: More marks.java:6: variable k might not have been initialized int[ ] marks = new int[k]; ^
  • 8. ARRAY SIZE THROUGH INPUT …. BufferedReader in1 = new BufferedReader (new InputStreamReader(System.in)); int num; System.out.println("Enter a Size for Array:"); num = Integer.parseInt(in1.readLine( ); int [ ] marks = new int[num]; System.out.println(“Array Length=”+marks.length); …. SAMPLE RUN: Enter a Size for Array: 4 Array Length=4
  • 9. 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
  • 10. ACCESSING ARRAY ELEMENTS  Index of an array is defined as  Positive int, byte or short values  Expression that results into these types  Any other types used for index will give error  long, double, etc.  Indexing starts from 0 and ends at N-1
  • 11. 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 ArrayIndexOutOfBoundException will be thrown  Program will normally be terminated unless handled in the try {} catch {}
  • 12. WHAT HAPPENS IF … int[] marks = new int[5]; marks[6]=33; …. Runtime Error: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 6 at marks.main(marks.java:6)
  • 13. REUSING ARRAY VARIABLES  Array variable is separate from array itself  Like a variable can refer to different values at different points in the program  Use array variables to access different arrays int[] marks=new int[5]; …… marks=new int[50];  Previous array will be discarded  Cannot alter the type of array
  • 14. INITIALIZING ARRAYS  Initialize and specify size of array while declaring an array variable int[] marks={2,3,5,7,11,13,17}; //7 elements  You can initialize array with an existing array int[] even={72,74,66,68,70}; 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
  • 15. GRAPHICAL REPRESENTATION 0 1 2 3 4 72 74 66 68 70 even value
  • 16. DEMONSTRATION int[] marks = new int[20]; marks[0] = 2; marks[1] = 3; int[] marks2=marks; System.out.println(marks2[0]); marks2[0]=5; System.out.println(marks[0]);
  • 18. ARRAY LENGTH  Refer to array length using length  A data member of array object  array_variable_name.length  for(int k=0; k<marks.length;k++) ….  Sample Code: int[] marks = new int[5]; System.out.println(marks.length); Output: 5
  • 19. CHANGE IN ARRAY LENGTH  If number of elements in the array are changed, JAVA will automatically change the length attribute!
  • 20. Changing the size of array is not possible! On changing the size of an existing array, a new array gets created at a different memory location.
  • 21. import java.io.*; class Array1{ public static void main(String args[])throws IOException { int n,i,noe; BufferedReader in1=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter no of array elements"); noe=Integer.parseInt(in1.readLine()); int arr[]=new int[noe]; System.out.println("Array details"+arr); System.out.println("Enter "+ noe+" array elements"); for(i=0;i<arr.length;i++) { arr[i]=Integer.parseInt(in1.readLine()); } System.out.println("Entered array elements are as follows:"); for(i=0;i<arr.length;i++) { System.out.print(" "+arr[i]); }
  • 22. System.out.println("nLets increase number of elements by 2 "); arr=new int[noe+2]; System.out.println("Array details after increased size"+arr); System.out.println("Enter "+ (noe+2)+" array elements"); for(i=0;i<arr.length;i++) { arr[i]=Integer.parseInt(in1.readLine()); } System.out.println("Entered array elements are as follows:"); for(i=0;i<arr.length;i++) { System.out.print(" "+arr[i]); } } }
  • 24. 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 ); } }
  • 25. 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
  • 26. INITIALIZING ARRAY OF ARRAYS int[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99} }; //7 arrays with 5 elements each
  • 27. ARRAYS OF ARRAYS OF VARYING LENGTH (JAGGED ARRAYS)  All arrays do not have to be of the same length float[][] samples; samples=new float[5][];//defines no of rows in an array samples[0]=new float[6]; samples[1]=new float[101];  Not required to define all arrays
  • 28. INITIALIZING VARYING SIZE ARRAYS int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; //Three arrays //First array has 3 elements //Second array has 2 elements //Third array has 5 elements
  • 29. To allocate memory for a 2D array, we need to specify the memory for the first(Leftmost) dimension. Then remaining dimensions can be allocated separately. For eg: int arr2d[][]=new int[3][]; arr2d[0]=new int[3]; arr2d[1]=new int[3]; arr2d[2]=new int[3]; Above declaration allocates memory for the first dimension of arr2d when it is declared. Then we allocate memory for the second dimension separately. There is no benefit of doing memory allocation this way in above example but it is helpful when we may want to allocate unequal number of elements across each row. An array created in this fashion in java is called Jagged Array.
  • 30. JAGGED ARRAY Class JaggedArray { public static void main(String args[]) { int twoD[][] = new int[4][]; twoD[0] = new int[1]; twoD[1] = new int[2]; twoD[2] = new int[3]; twoD[3] = new int[4]; int i, j, k = 0; for(i=0; i<4; i++) { for(j=0; j<i+1; j++) { twoD[i][j] = k; k++; } }
  • 31. for(i=0; i<4; i++) { for(j=0; j<i+1; j++) { System.out.print(twoD[i][j] + " "); } System.out.println(); } } } Output: 0 1 2 3 4 5 6 7 8 9
  • 32. 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(); } } }
  • 33. OUTPUT Row 0: 1 9 4 Row 1: 0 2 Row 2: 0 1 2 3 4
  • 34. TRIANGULAR ARRAY OF ARRAYS  Triangular Array for(int k=0; k<samples.length;k++) samples[k]=new float[k+1];
  • 35. MULTIDIMENSIONAL ARRAYS  A farmer has 10 farms of beans each in 5 countries, and each farm has 30 fields!  Three-dimensional array int[][][] beans=new int[5][10][30]; //beans[country][farm][fields]
  • 36. VARYING LENGTH IN MULTIDIMENSIONAL ARRAYS  Same features apply to multi-dimensional arrays as those of 2 dimensional arrays int beans=new int[3][][];//3 countries beans[0]=new int[4][];//First country has 4 farms beans[0][4]=new int[10]; //Each farm in first country has 10 fields
  • 37. Vector Vector is a legacy class available in java.util package. Vector implements a dynamic array. Here are the Vector constructors: Vector( ) Vector(int size) Vector(int size, int incr) The first form creates a default vector, which has an initial size of 10. The second form creates a vector whose initial capacity is specified by size. The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward.
  • 38. Important Points: 1. All vectors start with an initial capacity. 2. After this initial capacity is reached, the next time that you attempt to store an object in the vector, the vector automatically allocates space for that object plus extra room for additional objects. 3. By allocating more than just the required memory, the vector reduces the number of allocations that must take place. This reduction is important, because allocations are costly in terms of time. 4. The amount of extra space allocated during each reallocation is determined by the increment that you specify when you create the vector. 5. If you don’t specify an increment, the vector’s size is doubled by each allocation cycle.
  • 39. Vector defines these protected data members: int capacityIncrement; int elementCount; The increment value is stored in capacityIncrement. The number of elements currently in the vector is stored in elementCount. Vector defines several legacy methods, 1.void addElement(Object element): The object specified by element is added to the vector. 2. int capacity( ): Returns the capacity of the vector. 3. boolean contains(Object element): Returns true if element is contained by the vector, and returns false if it is not. 4. Object elementAt(int index): Returns the element at the location specified by index. 5. void ensureCapacity(int size) :Sets the minimum capacity of the vector to size.
  • 40. 6. Object firstElement( ): Returns the first element in the vector. 7. int indexOf(Object element) :Returns the index of the first occurrence of element. If the object is not in the vector, –1 is returned. 8. int indexOf(Object element, int start) Returns the index of the first occurrence of element at or after start. If the object is not in that portion of the vector -1 is returned. 9. void insertElementAt(Object element, int index): Adds element to the vector at the location specified by index. 10. boolean isEmpty( ): Returns true if the vector is empty and returns false if it contains one or more elements.
  • 41. 11. void removeAllElements( ): Empties the vector. After this method executes, the size of the vector is zero. 12. boolean removeElement(Object element): Removes element from the vector. If more than one instance of the specified object exists in the vector, then it is the first one that is removed. Returns true if successful and false if the object is not found. 13. void removeElementAt(int index): Removes the element at the location specified by index. 14. void setElementAt(Object element, int index):The location specified by index is assigned element. 15. void setSize(int size): Sets the number of elements in the vector to size. If the new size is less than the old size, elements are lost. If the new size is larger than the old size, null elements are added.
  • 42. // Demonstrate various Vector operations. import java.util.*; class VectorDemo { public static void main(String args[]) { // initial size is 3, increment is 2 Vector v = new Vector(3, 2); System.out.println("Initial size: " + v.size()); System.out.println("Initial capacity: " + v.capacity()); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); v.addElement(new Integer(4)); System.out.println("Capacity after 4 additions: " + v.capacity());
  • 43. v.addElement(new Double(5.45)); System.out.println("Current capacity: " +v.capacity()); v.addElement(new Double(6.08)); v.addElement(new Integer(7)); System.out.println("Current capacity: " +v.capacity()); v.addElement(new Float(9.4)); v.addElement(new Integer(10)); System.out.println("Current capacity: " +v.capacity()); v.addElement(new Integer(11)); v.addElement(new Integer(12)); System.out.println("First element: " +(Integer)v.firstElement()); System.out.println("Last element: " +(Integer)v.lastElement());
  • 44. if(v.contains(new Integer(3))) System.out.println("Vector contains 3."); // enumerate the elements in the vector. Enumeration vEnum = v.elements(); System.out.println("nElements in vector:"); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + " "); System.out.println(); } }
  • 45. The output from this program is shown here: Initial size: 0 Initial capacity: 3 Capacity after four additions: 5 Current capacity: 5 Current capacity: 7 Current capacity: 9 First element: 1 Last element: 12 Vector contains 3. Elements in vector: 1 2 3 4 5.45 6.08 7 9.4 10 11 12