SlideShare a Scribd company logo
Arrays in JAVA
Arrays
• An array is a container object that holds a
fixed number of values of a single type.
• The length of an array is established when the
array is created.
Creating and initializing an array.
 Making an array in a Java program involves three distinct
steps:
1. Declare the array name and type.
2. Create the array.
3. Initialize the array values.
Declare the array name and type.
• Do not have to create an array while declaring array variable
– <type> [] variable_name;
– int [] a;
– int a[];
• Both syntaxes are equivalent
• No memory allocation at this point
Create an array
• Create an array as follows:
– variable_name=new <type>[N];
– a=new int[10];
• Declaring and create in the same statement:
– int[] a=new int[10];
• In JAVA, int is of 4 bytes, total space=4*10=40 bytes
Initialize the array values
 Specifying the initialization values
 The default initial value
 Numeric types to zero for
 Boolean type to false.
 Char values to ‘u0000’ (unicode for blank character)
 Class types to null
int[] a = new int[10];
...
a[3] = -9;
...
Graphical Representation
0 1 2 3 4 5 6 7 8 9
2 1 11 -9 2 1 11 90 101 2
a
Index
value
What happens if …
 We define
int[] a=new long[20];
Morea.java:5: incompatible types
found: long[]
required: int[]
int[] a = new long[20];
^
 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=7;
long[] a = new long[k];
• Invalid Code:
int k;
long[] a =new long[k];
Compilation Output:
Morea.java:6: variable k might not have been
initialized
Array Size through Input
….
BufferedReader stdin = new BufferedReader (new
InputStreamReader(System.in));
String inData;
int num;
System.out.println("Enter a Size for Array:");
inData = stdin.readLine();
num = Integer.parseInt( inData ); // convert
inData to int
long[] a = new long[num];
System.out.println(“Array Length=”+a.length);
….
SAMPLE RUN:
Enter a Size for Array:
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.
 Incase Expression results in long, then type cast to int
 Indexing starts from 0 and ends at N-1
a[2]=0;
int k = a[2];
…
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
{}
What happens if …
long[] a= new long[20];
a[25]=33;
….
Runtime Error:
Exception in thread “main”
java.lang.ArrayIndexOutOfBoundsException:
25
at Morea.main(Morea.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[] a=new int[10];
……
a=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[] a={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
Graphical Representation
0 1 2 3 4
2 4 6 8 10
even
value
Demonstration
long[] a1 = new long[20];
a1[0] = 2;
a1[1] = 3;
long[] a2=a1;
System.out.println(a2[0]);
a2[0]=5;
System.out.println(a2[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<a.length;k++)
….
• Sample Code:
long[] a = new long[20];
System.out.println(a.length);
• Output: 20
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
Graphical Representation
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
Sample[0]
Sample[1]
Sample[2]
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} };
//5 arrays with 5 elements each
Arrays of Arrays of Varying Length
• All arrays do not have to be of the same length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=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
Array of Arrays Length
long[][] aa = new long[20][];
aa[2] = new long[30];
System.out.println(aa.length); //Number of
arrays
System.out.println(aa[2].length);//Number of
elements in the second array
OUTPUT:
20
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
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]
Varying length in Multidimensional
Arrays
• Same features apply to multi-dimensional
arrays as those of 2 dimensional arrays
long beans=new long[3][][];//3 countries
beans[0]=new long[4][];//First country has 4 farms
beans[0][4]=new long[10];
//Each farm in first country has 10 fields
Interview questions
• You are given an array with integers between 1 and 1,000,000. One
integer is in the array twice. How can you determine which one?
Can you think of a way to do it using extra memory?
Interview questions
• Solution 1: (extra memory, but faster)
1. Have a hash table
2. Go over the array and store its elements in hash table
3. As soon as you find an element which is already in hash table, it is the dup
element
• Solution2: (no extra memory, but slower)
1. Sort the array using merge sort (O(n log n) time)
2. Parse again and if you see a element twice you got the dup element.
Interview questions
• Return the sum two largest integers in an array
int SumTwoLargest(int* anData, int size)
• Sum n largest integers in an array of integers where every integer is
between 0 and 9
int SumNLargest(int* anData, int size, int n)

More Related Content

What's hot

An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
 
Array
ArrayArray
Array
PRN USM
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
bhavesh prakash
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Janpreet Singh
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
LATHA LAKSHMI
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
أحمد محمد
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in Python
Andrew Ferlitsch
 
Arrays
ArraysArrays
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
KristinaBorooah
 
Array data structure
Array data structureArray data structure
Array data structure
maamir farooq
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
Mahmoud Samir Fayed
 
Arrays
ArraysArrays
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Array ppt
Array pptArray ppt
Array ppt
Kaushal Mehta
 

What's hot (20)

An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Array lecture
Array lectureArray lecture
Array lecture
 
Array
ArrayArray
Array
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in Python
 
Arrays
ArraysArrays
Arrays
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Array data structure
Array data structureArray data structure
Array data structure
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
 
Arrays
ArraysArrays
Arrays
 
Java arrays
Java arraysJava arrays
Java arrays
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Array ppt
Array pptArray ppt
Array ppt
 

Viewers also liked

Java question bank
 Java question bank Java question bank
Java question bankhitzsmakz
 
5th Semester (December; January-2014 and 2015) Computer Science and Informati...
5th Semester (December; January-2014 and 2015) Computer Science and Informati...5th Semester (December; January-2014 and 2015) Computer Science and Informati...
5th Semester (December; January-2014 and 2015) Computer Science and Informati...
BGS Institute of Technology, Adichunchanagiri University (ACU)
 
BMS 5th SEM Question Paper:-Logistic & SCM
BMS 5th SEM Question Paper:-Logistic & SCMBMS 5th SEM Question Paper:-Logistic & SCM
BMS 5th SEM Question Paper:-Logistic & SCM
Yogesh Dalvi
 
BMS 5th SEM Question Paper:- Ethics & Governance
BMS 5th SEM Question Paper:- Ethics & GovernanceBMS 5th SEM Question Paper:- Ethics & Governance
BMS 5th SEM Question Paper:- Ethics & Governance
Yogesh Dalvi
 

Viewers also liked (8)

Java question bank
 Java question bank Java question bank
Java question bank
 
5th Semester CS / IS (2013-June) Question Papers
5th Semester CS / IS (2013-June) Question Papers5th Semester CS / IS (2013-June) Question Papers
5th Semester CS / IS (2013-June) Question Papers
 
5th Semester (December; January-2014 and 2015) Computer Science and Informati...
5th Semester (December; January-2014 and 2015) Computer Science and Informati...5th Semester (December; January-2014 and 2015) Computer Science and Informati...
5th Semester (December; January-2014 and 2015) Computer Science and Informati...
 
Question bank
Question bankQuestion bank
Question bank
 
BMS 5th SEM Question Paper:-Logistic & SCM
BMS 5th SEM Question Paper:-Logistic & SCMBMS 5th SEM Question Paper:-Logistic & SCM
BMS 5th SEM Question Paper:-Logistic & SCM
 
BMS 5th SEM Question Paper:- Ethics & Governance
BMS 5th SEM Question Paper:- Ethics & GovernanceBMS 5th SEM Question Paper:- Ethics & Governance
BMS 5th SEM Question Paper:- Ethics & Governance
 
1st Semester M Tech Structural Engineering (Dec-2013) Question Papers
1st Semester M Tech Structural Engineering  (Dec-2013) Question Papers 1st Semester M Tech Structural Engineering  (Dec-2013) Question Papers
1st Semester M Tech Structural Engineering (Dec-2013) Question Papers
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 

Similar to 6 arrays injava

07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
أحمد محمد
 
L10 array
L10 arrayL10 array
L10 array
teach4uin
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01Abdul Samee
 
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
JayanthiM19
 
Core java day2
Core java day2Core java day2
Core java day2
Soham Sengupta
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Chap 6 c++Chap 6 c++
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Java introduction
Java introductionJava introduction
Java introduction
Samsung Electronics Egypt
 
Arrays In General
Arrays In GeneralArrays In General
Arrays In Generalmartha leon
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
Mrhaider4
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1sotlsoc
 
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
Kuntal Bhowmick
 
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
Kuntal Bhowmick
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arraysAseelhalees
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
ShahinAhmed49
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
Mahyuddin8
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
SHASHIKANT346021
 

Similar to 6 arrays injava (20)

07 Arrays
07 Arrays07 Arrays
07 Arrays
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
L10 array
L10 arrayL10 array
L10 array
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
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
 
Core java day2
Core java day2Core java day2
Core java day2
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Java introduction
Java introductionJava introduction
Java introduction
 
Array
ArrayArray
Array
 
Arrays In General
Arrays In GeneralArrays In General
Arrays In General
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
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
 
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
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
 
ch07-arrays.ppt
ch07-arrays.pptch07-arrays.ppt
ch07-arrays.ppt
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 

More from irdginfo

Quicksort Presentation
Quicksort PresentationQuicksort Presentation
Quicksort Presentation
irdginfo
 
10 merge sort
10 merge sort10 merge sort
10 merge sortirdginfo
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notationirdginfo
 
8 elementary sorts-bubble
8 elementary sorts-bubble8 elementary sorts-bubble
8 elementary sorts-bubbleirdginfo
 
8 elementary sorts-shell
8 elementary sorts-shell8 elementary sorts-shell
8 elementary sorts-shellirdginfo
 
8 elementary sorts-insertion
8 elementary sorts-insertion8 elementary sorts-insertion
8 elementary sorts-insertionirdginfo
 
8 elementary sorts-selection
8 elementary sorts-selection8 elementary sorts-selection
8 elementary sorts-selectionirdginfo
 
7 searching injava-binary
7 searching injava-binary7 searching injava-binary
7 searching injava-binaryirdginfo
 
5 data structures-hashtable
5 data structures-hashtable5 data structures-hashtable
5 data structures-hashtableirdginfo
 
5 data structures-tree
5 data structures-tree5 data structures-tree
5 data structures-treeirdginfo
 
5 data structures-stack
5 data structures-stack5 data structures-stack
5 data structures-stackirdginfo
 
5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlistirdginfo
 
4 character encoding-unicode
4 character encoding-unicode4 character encoding-unicode
4 character encoding-unicodeirdginfo
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-asciiirdginfo
 
4 character encoding
4 character encoding4 character encoding
4 character encodingirdginfo
 
3 number systems-floatingpoint
3 number systems-floatingpoint3 number systems-floatingpoint
3 number systems-floatingpointirdginfo
 
2 number systems-scientificnotation
2 number systems-scientificnotation2 number systems-scientificnotation
2 number systems-scientificnotationirdginfo
 
1 number systems-hex
1 number systems-hex1 number systems-hex
1 number systems-hexirdginfo
 
1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegersirdginfo
 
1 number systems-octal
1 number systems-octal1 number systems-octal
1 number systems-octalirdginfo
 

More from irdginfo (20)

Quicksort Presentation
Quicksort PresentationQuicksort Presentation
Quicksort Presentation
 
10 merge sort
10 merge sort10 merge sort
10 merge sort
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notation
 
8 elementary sorts-bubble
8 elementary sorts-bubble8 elementary sorts-bubble
8 elementary sorts-bubble
 
8 elementary sorts-shell
8 elementary sorts-shell8 elementary sorts-shell
8 elementary sorts-shell
 
8 elementary sorts-insertion
8 elementary sorts-insertion8 elementary sorts-insertion
8 elementary sorts-insertion
 
8 elementary sorts-selection
8 elementary sorts-selection8 elementary sorts-selection
8 elementary sorts-selection
 
7 searching injava-binary
7 searching injava-binary7 searching injava-binary
7 searching injava-binary
 
5 data structures-hashtable
5 data structures-hashtable5 data structures-hashtable
5 data structures-hashtable
 
5 data structures-tree
5 data structures-tree5 data structures-tree
5 data structures-tree
 
5 data structures-stack
5 data structures-stack5 data structures-stack
5 data structures-stack
 
5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist5 data structures-arraysandlinkedlist
5 data structures-arraysandlinkedlist
 
4 character encoding-unicode
4 character encoding-unicode4 character encoding-unicode
4 character encoding-unicode
 
4 character encoding-ascii
4 character encoding-ascii4 character encoding-ascii
4 character encoding-ascii
 
4 character encoding
4 character encoding4 character encoding
4 character encoding
 
3 number systems-floatingpoint
3 number systems-floatingpoint3 number systems-floatingpoint
3 number systems-floatingpoint
 
2 number systems-scientificnotation
2 number systems-scientificnotation2 number systems-scientificnotation
2 number systems-scientificnotation
 
1 number systems-hex
1 number systems-hex1 number systems-hex
1 number systems-hex
 
1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers1 number systems-unsignedsignedintegers
1 number systems-unsignedsignedintegers
 
1 number systems-octal
1 number systems-octal1 number systems-octal
1 number systems-octal
 

Recently uploaded

Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 

Recently uploaded (20)

Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 

6 arrays injava

  • 2. Arrays • An array is a container object that holds a fixed number of values of a single type. • The length of an array is established when the array is created.
  • 3. Creating and initializing an array.  Making an array in a Java program involves three distinct steps: 1. Declare the array name and type. 2. Create the array. 3. Initialize the array values.
  • 4. Declare the array name and type. • Do not have to create an array while declaring array variable – <type> [] variable_name; – int [] a; – int a[]; • Both syntaxes are equivalent • No memory allocation at this point
  • 5. Create an array • Create an array as follows: – variable_name=new <type>[N]; – a=new int[10]; • Declaring and create in the same statement: – int[] a=new int[10]; • In JAVA, int is of 4 bytes, total space=4*10=40 bytes
  • 6. Initialize the array values  Specifying the initialization values  The default initial value  Numeric types to zero for  Boolean type to false.  Char values to ‘u0000’ (unicode for blank character)  Class types to null int[] a = new int[10]; ... a[3] = -9; ...
  • 7.
  • 8. Graphical Representation 0 1 2 3 4 5 6 7 8 9 2 1 11 -9 2 1 11 90 101 2 a Index value
  • 9. What happens if …  We define int[] a=new long[20]; Morea.java:5: incompatible types found: long[] required: int[] int[] a = new long[20]; ^  The right hand side defines an array, and thus the array variable should refer to the same type of array
  • 10. What happens if … • Valid code: int k=7; long[] a = new long[k]; • Invalid Code: int k; long[] a =new long[k]; Compilation Output: Morea.java:6: variable k might not have been initialized
  • 11. Array Size through Input …. BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); String inData; int num; System.out.println("Enter a Size for Array:"); inData = stdin.readLine(); num = Integer.parseInt( inData ); // convert inData to int long[] a = new long[num]; System.out.println(“Array Length=”+a.length); …. SAMPLE RUN: Enter a Size for Array:
  • 12. 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.  Incase Expression results in long, then type cast to int  Indexing starts from 0 and ends at N-1 a[2]=0; int k = a[2]; …
  • 13. 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 {}
  • 14. What happens if … long[] a= new long[20]; a[25]=33; …. Runtime Error: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 25 at Morea.main(Morea.java:6)
  • 15. 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[] a=new int[10]; …… a=new int[50];  Previous array will be discarded  Cannot alter the type of array
  • 16. Initializing Arrays  Initialize and specify size of array while declaring an array variable int[] a={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
  • 17. Graphical Representation 0 1 2 3 4 2 4 6 8 10 even value
  • 18. Demonstration long[] a1 = new long[20]; a1[0] = 2; a1[1] = 3; long[] a2=a1; System.out.println(a2[0]); a2[0]=5; System.out.println(a2[0]);
  • 20. Array Length • Refer to array length using length – A data member of array object – array_variable_name.length – for(int k=0; k<a.length;k++) …. • Sample Code: long[] a = new long[20]; System.out.println(a.length); • Output: 20
  • 21. 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
  • 22. Graphical Representation 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 Sample[0] Sample[1] Sample[2]
  • 23. 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} }; //5 arrays with 5 elements each
  • 24. Arrays of Arrays of Varying Length • All arrays do not have to be of the same length float[][] samples; samples=new float[6][];//defines # of arrays samples[2]=new float[6]; samples[5]=new float[101]; • Not required to define all arrays
  • 25. 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
  • 26. Array of Arrays Length long[][] aa = new long[20][]; aa[2] = new long[30]; System.out.println(aa.length); //Number of arrays System.out.println(aa[2].length);//Number of elements in the second array OUTPUT: 20
  • 27. 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(); } } }
  • 28. Output Row 0: 1 9 4 Row 1: 0 2 Row 2: 0 1 2 3 4
  • 29. 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]
  • 30. Varying length in Multidimensional Arrays • Same features apply to multi-dimensional arrays as those of 2 dimensional arrays long beans=new long[3][][];//3 countries beans[0]=new long[4][];//First country has 4 farms beans[0][4]=new long[10]; //Each farm in first country has 10 fields
  • 31. Interview questions • You are given an array with integers between 1 and 1,000,000. One integer is in the array twice. How can you determine which one? Can you think of a way to do it using extra memory?
  • 32. Interview questions • Solution 1: (extra memory, but faster) 1. Have a hash table 2. Go over the array and store its elements in hash table 3. As soon as you find an element which is already in hash table, it is the dup element • Solution2: (no extra memory, but slower) 1. Sort the array using merge sort (O(n log n) time) 2. Parse again and if you see a element twice you got the dup element.
  • 33. Interview questions • Return the sum two largest integers in an array int SumTwoLargest(int* anData, int size) • Sum n largest integers in an array of integers where every integer is between 0 and 9 int SumNLargest(int* anData, int size, int n)