0% found this document useful (0 votes)
6 views

Arrays

The document provides an introduction to arrays in Java, covering their advantages, disadvantages, and how to declare and initialize them. It includes examples of single-dimensional and multi-dimensional arrays, as well as operations like passing arrays to methods and copying arrays. Additionally, the document discusses Java enums and vectors, highlighting their characteristics and differences from ArrayLists.

Uploaded by

Trupti Dave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Arrays

The document provides an introduction to arrays in Java, covering their advantages, disadvantages, and how to declare and initialize them. It includes examples of single-dimensional and multi-dimensional arrays, as well as operations like passing arrays to methods and copying arrays. Additionally, the document discusses Java enums and vectors, highlighting their characteristics and differences from ArrayLists.

Uploaded by

Trupti Dave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

TODAY’S SESSION:

About Arrays

Declaring Array
INTRODUCTION TO ARRAY

• Arrays are fundamental structures in Java


that allow us to store multiple values of the
same type in a single variable.
• They are useful for storing and managing
collections of data.
INTRODUCTION TO ARRAY
ADVANTAGE OF JAVA ARRAY

• Code Optimization: It makes the code


optimized, we can retrieve or sort the data
easily.
• Random access: We can get any data
located at any index position.
DISADVANTAGE OF JAVA ARRAY

• Size Limit: We can store only fixed size of


elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection
framework is used in java
DECLARING ARRAY VARIABLES

• There are some basic operations we can start with as mentioned


below:
1. Array Declaration
• To declare an array in Java, use the following syntax:
datatype arrayName[];
type: The data type of the array elements (e.g., int, String).
arrayName: The name of the array.
Note: The array is not yet initialized.
DECLARING ARRAY VARIABLES

2. Create an Array
• To create an array, you need to allocate memory for it using the
new keyword:

// Creating an array of 5 integers


int[] numbers = new int[5];

• This statement initializes the numbers array to hold 5 integers. The


default value for each element is 0.
DECLARING ARRAY VARIABLES

• Example:
int m[]= new int[10];
Here m is an array that can store 10 data items in the memory
with different subscripts. M is the Subscripted Variable and 0 to 9
are the subscripts
M
M M M2 M9
0 1
EXAMPLE
public class Array{ Outp
public static void main(String[] args) ut
{
// initializing array
int arr[] = { 1, 2, 3, 4, 5 };
// size of array
int n = arr.length;
// traversing array
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
TASK

• Write a Java program to initialize an array


with the first five odd numbers and calculate
the sum of all the numbers of the array.
CHALLENGE

• Write a Java program to accept 20 integer


numbers and calculate the sum of all the
numbers of the array.
HTTPS://WWW.SLIDESERVE.COM/EDUREKAIN/ARRAYS-IN-
JAVA-INTRODUCTION-TO-JAVA-ARRAYS-JAVA-
PROGRAMMING-EDUREKA-POWERPOINT-PPT-
PRESENTATION
FOR LOOP: EXAMPLE
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 0; i < myList.length; i++)
{
System.out.println(myList[i] + " ");
}

double total = 0;
for (int i = 0; i < myList.length; i++)
{
total += myList[i];
}
System.out.println("Total is " + total);

double max = myList[0];


for (int i = 1; i < myList.length; i++)
{
if (myList[i] > max)
max = myList[i];
}
• Output
• 1.9
• 2.9
• 3.4
• 3.5
• Total is 11.7
• Max is 3.5
TYPES OF ARRAY IN JAVA

• Single Dimensional Array in java

• Syntax to Declare an Array in java


• dataType[] arr; (or)
• dataType []arr; (or)
• dataType arr[];
• Instantiation of an Array in java

• arrayRefVar=new datatype[size];
class Testarray{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}

Output:
10
20
70
40
50
PASSING ARRAY TO METHOD IN JAVA
class Testarray2
{
static void minimum(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int arr[]={33,3,4,5};
minimum(arr);//passing array to method
}}

Output: 3
MULTIDIMENSIONAL ARRAY IN JAVA

• dataType[][] arrayRefVar; (or)


• dataType [][]arrayRefVar; (or)
• dataType arrayRefVar[][]; (or)
• dataType []arrayRefVar[];
• int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java


• arr[0][0]=1;
• arr[0][1]=2;
• arr[0][2]=3;
• arr[1][0]=4;
• arr[1][1]=5;
• arr[1][2]=6;
• arr[2][0]=7;
• arr[2][1]=8;
• arr[2][2]=9;
class Testarray3
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
} }}

Output:
123
245
445
COPYING A JAVA ARRAY

class TestArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}

Output: caffein
JAVA ENUM

• Enum in java is a data type that contains fixed set of constants.


• It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST) etc. The java enum constants are static and final
implicitly. It is available from JDK 1.5.
• Java Enums can be thought of as classes that have fixed set of constants.
POINTS TO REMEMBER FOR JAVA ENUM

• enum improves type safety


• enum can be easily used in switch
• enum can be traversed
• enum can have fields, constructors and methods
• enum may implement many interfaces but cannot extend
any class because it internally extends Enum class
class EnumExample1
{
public enum Season { WINTER, SPRING, SUMMER,
FALL }
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);
}}

Output:
WINTER
Introduction to Vectors

• Vector implements a dynamic array.


• Vector is synchronized.
• Vector contains many legacy methods that are not part of the
collections framework.
DIFFERENCE BETWEEN ARRAYLIST AND
VECTOR
ArrayList Vector

1) ArrayList is not Vector is synchronized.


synchronized.
2) ArrayList increments Vector increments
50% of current array size if 100% means doubles the
number of element exceeds array size if total number of
from its capacity. element exceeds than its
capacity.
3) ArrayList is not a Vector is
legacy class, it is introduced a legacy class(includes only
in JDK 1.2. classes and interfaces).
4) ArrayList is fast because it Vector is slow because it is
is non-synchronized. synchronized.
• Declaration
• Following is the declaration for java.util.Vector.addElement() method
• public void addElement(E obj)
• Parameters
• obj -- It refers to the component to be added.
• Return Value
• The return type is void
import java.util.*;
class TestVector1
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>(); //creating vector
v.add("umesh"); //method of Collection
v.addElement("irfan"); //method of Vector
v.addElement("kumar");
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
} }}

• Output:
umesh irfan kumar
Accessing Vector Elements
import java.util.Vector;
public class VectorDemo
{
public static void main(String[] args)
{
// create an empty Vector vec with an initial capacity of 4
Vector vec = new Vector(4);
// use add() method to add elements in the vector
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);
// let us get the 3rd element of the vector
System.out.println("Third element is :"+vec.get(3));
}}
Searching For Elements In A
import java.util.Vector;
Vector
public class VectorDemo
{
public static void main(String[] args)
{
// create an empty Vector vec with an initial capacity of 4
Vector vec = new Vector(4);
// use add() method to add elements in the vector
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(3);
// let us get the index of 3
System.out.println("Index of 3 is :"+vec.indexOf(3));
}
}
import java.util.Vector; Working With The Size of The
Vector
public class VectorDemo
{
public static void main(String[] args)
{
// create an empty Vector vec with an initial capacity of 4
Vector vec = new Vector(4);

// use add() method to add elements in the vector


vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);

// let us print the size of the vector


System.out.println("Size of the vector: "+vec.size());
}
}

Size of the vector: 4

You might also like