SlideShare una empresa de Scribd logo
1 de 15
Java Programming
Manish Kumar
(manish87it@gmail.com)
Lecture- 7
Java arrays
Contents
 Introduction to Array
 One Dimensional Array
 ArrayIndexOutOfBoundsException
 Multi-Dimensional Array
 Passing Array to a method
 Jagged Array
 Class Name of Array
arrays
 As we are study earlier, an array is a collection of similar type of elements which has contiguous memory
location.
 Java Array is an object which contains elements of similar data-type and stored contiguously in memory.
 Each items in an array is called element and each element is accessed by its numerical index. The index of
an array begins with zero(0).
arrays
Following are some important points about Java Arrays:
 In java all arrays are dynamically allocated.
 Since Java Array is an object, therefore we can find their length using the object property length.
 Java array can also be used as static field, a local variable or a method parameter.
 Java Array inherits the Object class and implements the Serializable as well as Cloneable interfaces. We
can store primitive values or objects in an array in Java.
Types of Array
 One Dimensional Array
 Multi Dimensional Array
One dimensional array
Syntax to Declare one dimensional Array:
<Data-Type> <Array-Name>[];
OR
<Data-Type>[] <Array-Name>;
Instantiation of Array:
ArrayRefVar = new <Data-Type>[Size];
Example –
int arr[]; // Declaration of array
arr = new int[10]; // Initialization of array
OR int arr[] = new int[10] // Declaration and initialization
OR
int arr[] = {10,20,30};
One dimensional array
//ArrayDemo1.java
class ArrayDemo1 {
public static void main(String args[]) {
int arr[];
arr = new int[5];
arr[0] = 10;
arr[1] = 11;
arr[2] = 12;
arr[3] = 13;
arr[4] = 14;
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Output-
10
11
12
13
14
//ArrayDemo2.java
class ArrayDemo2 {
public static void main(String args[]) {
int arr[] = {10,20,30,40,50};
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Output-
10
20
30
40
50
One dimensional array
//ArrayDemo3.java
import java.util.Scanner;
class ArrayDemo3 {
public static void main(String args[]) {
int n, sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in array: ");
n = sc.nextInt();
int arr[] =new int[n];
System.out.println("Enter all the Elements: ");
for(int i=0; i<arr.length; i++) {
arr[i] = sc.nextInt();
sum = sum+arr[i];
}
System.out.println("Sum of all the Elements = "+sum);
}}
Output-
Enter the number of elements in array:
4
Enter all the Elements:
23
23
23
23
Sum of all the Elements = 92
Input through Keyboard in Java Array.
One dimensional array
Passing an array as a parameter to a
Method in java
//ArrayDemo4.java
class ArrayDemo4 {
void display(int ar[]) {
for(int i=0; i<ar.length; i++) {
System.out.println(ar[i]);
}
}
public static void main(String args[]) {
ArrayDemo ad = new ArrayDemo();
int a[] = {10,20,30};
ad.display(a);
}
}
Output-
10
20
30
One dimensional array
ArrayIndexOutOfBoundsException
If length of the array in negative, equal to
the array size or greater than the array size
while traversing the array.
//ArrayDemo5.java
class ArrayDemo4 {
void display(int ar[]) {
for(int i=0; i<=ar.length; i++) {
System.out.println(ar[i]);
}
}
public static void main(String args[]) {
ArrayDemo ad = new ArrayDemo();
int a[] = {10,20,30};
ad.display(a);
}
}
Output-
10
20
30
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 3
at ArrayDemo.display(ArrayDemo.java:4)
at ArrayDemo.main(ArrayDemo.java:10)
Multi - dimensional array
In Multi – Dimensional Array, Data are stored in the form of table i.e., row and column or we can say that
in the form of matrix.
Syntax of Declaration
<DataType>[][] arr (or) <DataType> arr[][]; (or) <DataType> []arr[];
Instantiate Multidimensional Array in Java
int [][]arr = new int[3][3]; // 3 row and 3 column
First index represent the Row and Second represent the column.
arr[0][0] arr[0][1] arr[0][2]
arr[1][0] arr[1][1] arr[1][2]
arr[2][0] arr[2][1] arr[2][2]
Multi - dimensional array
//TwoDArray1.java
class TwoDArray1 {
public static void main(String args[]){
int ar[][] = {{10,20,30},{40,50,60},{70,80,90}};
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
System.out.print(ar[i][j]+" ");
}
System.out.println();
}
}
}
Output-
10 20 30
40 50 60
70 80 90
Multi - dimensional array
//TwoDArray2.java
import java.util.Scanner;
class TwoDArray2 {
public static void main(String args[]){
int ar[][] = new int[3][3];
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array's Elements :");
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
ar[i][j] = sc.nextInt();
System.out.println("ar["+i+"]["+j+"] = "+" "+ar[i][j]);
}
System.out.println();
}}
}
Enter Array's Elements :
12
ar[0][0] = 12
13
ar[0][1] = 13
14
ar[0][2] = 14
16
ar[1][0] = 16
18
ar[1][1] = 18
19
ar[1][2] = 19
20
ar[2][0] = 20
21
ar[2][1] = 21
22
ar[2][2] = 22
Jagged array
Jagged Array is array of arrays such that member
arrays can be of different sizes, i.e., we can create a
2-D arrays but with variable number of columns in
each row. These type of arrays are also known as
Jagged arrays.
//TwoDArray3.java
class TwoDArray3 {
public static void main(String[] args) {
int arr[][] = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
System.out.println("Contents of 2D Jagged Array");
for (int i=0; i<arr.length; i++) {
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
} }
}
Output-
Contents of 2D Jagged Array
0 1 2
3 4
Class name of java array
In Java, an array is an object. For array object, a
proxy class is created whose name can be
obtained by getClass().getName() method on the
object.
//TwoDArray4.java
class TwoDArray4 {
public static void main(String[] args) {
int arr[]={10,20,30};
Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
}
}
Output -
[I
Lecture   7 arrays

Más contenido relacionado

La actualidad más candente (20)

Java interfaces
Java interfacesJava interfaces
Java interfaces
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Data types in java
Data types in javaData types in java
Data types in java
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Java arrays
Java arraysJava arrays
Java arrays
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Java swing
Java swingJava swing
Java swing
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 

Similar a Lecture 7 arrays

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 stringsKuntal 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 stringsKuntal Bhowmick
 
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 arraysJayanthiM19
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
Write an application that stores 12 integers in an array. Display the.docx
 Write an application that stores 12 integers in an array. Display the.docx Write an application that stores 12 integers in an array. Display the.docx
Write an application that stores 12 integers in an array. Display the.docxajoy21
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Sunil Kumar Gunasekaran
 
Operators
OperatorsOperators
Operatorsvvpadhu
 
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 technologyworldchannel
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: ArraysSvetlin Nakov
 

Similar a Lecture 7 arrays (20)

Java Programming
Java ProgrammingJava Programming
Java Programming
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
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
 
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
 
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
ArraysArrays
Arrays
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Write an application that stores 12 integers in an array. Display the.docx
 Write an application that stores 12 integers in an array. Display the.docx Write an application that stores 12 integers in an array. Display the.docx
Write an application that stores 12 integers in an array. Display the.docx
 
Array
ArrayArray
Array
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Operators
OperatorsOperators
Operators
 
Python array
Python arrayPython array
Python 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
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
 

Más de manish kumar

Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packagesmanish kumar
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interfacemanish kumar
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statementmanish kumar
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMmanish kumar
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to javamanish kumar
 

Más de manish kumar (8)

Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVM
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to java
 

Último

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 

Último (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

Lecture 7 arrays

  • 2. Contents  Introduction to Array  One Dimensional Array  ArrayIndexOutOfBoundsException  Multi-Dimensional Array  Passing Array to a method  Jagged Array  Class Name of Array
  • 3. arrays  As we are study earlier, an array is a collection of similar type of elements which has contiguous memory location.  Java Array is an object which contains elements of similar data-type and stored contiguously in memory.  Each items in an array is called element and each element is accessed by its numerical index. The index of an array begins with zero(0).
  • 4. arrays Following are some important points about Java Arrays:  In java all arrays are dynamically allocated.  Since Java Array is an object, therefore we can find their length using the object property length.  Java array can also be used as static field, a local variable or a method parameter.  Java Array inherits the Object class and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Types of Array  One Dimensional Array  Multi Dimensional Array
  • 5. One dimensional array Syntax to Declare one dimensional Array: <Data-Type> <Array-Name>[]; OR <Data-Type>[] <Array-Name>; Instantiation of Array: ArrayRefVar = new <Data-Type>[Size]; Example – int arr[]; // Declaration of array arr = new int[10]; // Initialization of array OR int arr[] = new int[10] // Declaration and initialization OR int arr[] = {10,20,30};
  • 6. One dimensional array //ArrayDemo1.java class ArrayDemo1 { public static void main(String args[]) { int arr[]; arr = new int[5]; arr[0] = 10; arr[1] = 11; arr[2] = 12; arr[3] = 13; arr[4] = 14; for(int i=0; i<arr.length; i++) { System.out.println(arr[i]); } } } Output- 10 11 12 13 14 //ArrayDemo2.java class ArrayDemo2 { public static void main(String args[]) { int arr[] = {10,20,30,40,50}; for(int i=0; i<arr.length; i++) { System.out.println(arr[i]); } } } Output- 10 20 30 40 50
  • 7. One dimensional array //ArrayDemo3.java import java.util.Scanner; class ArrayDemo3 { public static void main(String args[]) { int n, sum = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements in array: "); n = sc.nextInt(); int arr[] =new int[n]; System.out.println("Enter all the Elements: "); for(int i=0; i<arr.length; i++) { arr[i] = sc.nextInt(); sum = sum+arr[i]; } System.out.println("Sum of all the Elements = "+sum); }} Output- Enter the number of elements in array: 4 Enter all the Elements: 23 23 23 23 Sum of all the Elements = 92 Input through Keyboard in Java Array.
  • 8. One dimensional array Passing an array as a parameter to a Method in java //ArrayDemo4.java class ArrayDemo4 { void display(int ar[]) { for(int i=0; i<ar.length; i++) { System.out.println(ar[i]); } } public static void main(String args[]) { ArrayDemo ad = new ArrayDemo(); int a[] = {10,20,30}; ad.display(a); } } Output- 10 20 30
  • 9. One dimensional array ArrayIndexOutOfBoundsException If length of the array in negative, equal to the array size or greater than the array size while traversing the array. //ArrayDemo5.java class ArrayDemo4 { void display(int ar[]) { for(int i=0; i<=ar.length; i++) { System.out.println(ar[i]); } } public static void main(String args[]) { ArrayDemo ad = new ArrayDemo(); int a[] = {10,20,30}; ad.display(a); } } Output- 10 20 30 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at ArrayDemo.display(ArrayDemo.java:4) at ArrayDemo.main(ArrayDemo.java:10)
  • 10. Multi - dimensional array In Multi – Dimensional Array, Data are stored in the form of table i.e., row and column or we can say that in the form of matrix. Syntax of Declaration <DataType>[][] arr (or) <DataType> arr[][]; (or) <DataType> []arr[]; Instantiate Multidimensional Array in Java int [][]arr = new int[3][3]; // 3 row and 3 column First index represent the Row and Second represent the column. arr[0][0] arr[0][1] arr[0][2] arr[1][0] arr[1][1] arr[1][2] arr[2][0] arr[2][1] arr[2][2]
  • 11. Multi - dimensional array //TwoDArray1.java class TwoDArray1 { public static void main(String args[]){ int ar[][] = {{10,20,30},{40,50,60},{70,80,90}}; for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { System.out.print(ar[i][j]+" "); } System.out.println(); } } } Output- 10 20 30 40 50 60 70 80 90
  • 12. Multi - dimensional array //TwoDArray2.java import java.util.Scanner; class TwoDArray2 { public static void main(String args[]){ int ar[][] = new int[3][3]; Scanner sc = new Scanner(System.in); System.out.println("Enter Array's Elements :"); for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { ar[i][j] = sc.nextInt(); System.out.println("ar["+i+"]["+j+"] = "+" "+ar[i][j]); } System.out.println(); }} } Enter Array's Elements : 12 ar[0][0] = 12 13 ar[0][1] = 13 14 ar[0][2] = 14 16 ar[1][0] = 16 18 ar[1][1] = 18 19 ar[1][2] = 19 20 ar[2][0] = 20 21 ar[2][1] = 21 22 ar[2][2] = 22
  • 13. Jagged array Jagged Array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays. //TwoDArray3.java class TwoDArray3 { public static void main(String[] args) { int arr[][] = new int[2][]; arr[0] = new int[3]; arr[1] = new int[2]; int count = 0; for (int i=0; i<arr.length; i++) for(int j=0; j<arr[i].length; j++) arr[i][j] = count++; System.out.println("Contents of 2D Jagged Array"); for (int i=0; i<arr.length; i++) { for (int j=0; j<arr[i].length; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } } Output- Contents of 2D Jagged Array 0 1 2 3 4
  • 14. Class name of java array In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by getClass().getName() method on the object. //TwoDArray4.java class TwoDArray4 { public static void main(String[] args) { int arr[]={10,20,30}; Class c=arr.getClass(); String name=c.getName(); System.out.println(name); } } Output - [I