0% found this document useful (0 votes)
24 views43 pages

Java Arrays: Types and Usage Guide

The document provides a comprehensive overview of arrays in Java, including one-dimensional, multidimensional, and irregular arrays, as well as concepts like array references and memory allocation. It also covers the Java Collection Framework, focusing on ArrayLists and Vector classes, detailing their functionalities and differences. Additionally, it includes examples and syntax for declaring, initializing, and manipulating arrays and collections.

Uploaded by

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

Java Arrays: Types and Usage Guide

The document provides a comprehensive overview of arrays in Java, including one-dimensional, multidimensional, and irregular arrays, as well as concepts like array references and memory allocation. It also covers the Java Collection Framework, focusing on ArrayLists and Vector classes, detailing their functionalities and differences. Additionally, it includes examples and syntax for declaring, initializing, and manipulating arrays and collections.

Uploaded by

kukytare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA

Arrays

Mr D Siva Krishna
Assistant Professor

CSE, GST, VISAKHAPATNAM


CONTENT to be Discussed
⮚ 1D Arrays

⮚ Multidimensional Arrays

⮚ Irregular Arrays

⮚ Array References

⮚ Using the Length Member

⮚ Arrays class of util package

⮚ Array Lists

⮚ Vector class
Introduction to Arrays

• An array is a collection of fixed number of


elements of the same data type, referred to by a
common name.
• Array elements are always stored in contiguous
memory locations.
• Arrays can be categorized to one, two and
multidimensional arrays,
• Arrays in java are also objects.
Declaring an Array variable

datatype [ ] arrayName;
• This line declares an array but doesn’t allocate memory.
• dataType[ ] – Specifies the type of elements the array will hold (e.g., int, double, String, etc.).
The [ ] after the data type indicates that this is an array.
• arrayName – The name of the array variable that will reference the array.
• After this line, arrayName is declared as an array of dataType, but it do not point to any
allocated memory.
• The array itself is still null.
Array variable memory allocation

arrayName = new dataType[size];


• It is used to initialize an array by allocating memory for it. Let’s break down what each part of
this line does
• arrayName: This is the name of the array variable that has already been declared. It will
reference (or "point to") the newly created array.
• new: The new keyword is used to allocate memory in Java. It creates the array in memory.
• dataType: This is the type of elements that the array will hold, such as int, double, String, etc.
• size: This is the number of elements the array will hold. It must be a positive integer, indicating
the size of the array.
Array variable memory allocation

arrayName = new dataType[size];


Important Notes
• After this line, arrayName will refer to an array with size elements.
• Each element of the array is initialized to the default value of dataType:
• 0 for numeric types (like int, double, etc.).
• false for boolean.
• null for reference types (like String, Integer, etc.).
• Demo Program: assign_values_arrays.java
Array variable memory allocation

Example: Store student scores in an array.


Accessing Elements: Use an index to access elements
int score = numbers[0];

Program: Write a java program to store the score of top 10 students


student_score_arrays.java
One Dimensional Arrays

• A one-dimensional array is a linear collection of elements.


Declaration and Initialization:
• Syntax to declare a one-dimensional array
type[ ] array-name = new type[size];

Here is an example. The following creates an int array of 10 elements and links it to an array
reference variable named sample.
int[] numbers = new int[10];
Initialization numbers[0] = 10; // Initialization
One Dimensional Arrays
ONE DIMENSIONAL ARRAYS
public class ArrayExample {
public static void main(String[] args) {
int [ ] numbers; // Declares an array of integers
numbers = new int [5]; // Initializes the array with a size of 5

// Assign values to each element


numbers[0] = 10; numbers[1] = 20;
numbers[2] = 30; numbers[3] = 40;
numbers[4] = 50;

// Print array elements


for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
} } }
[Link]
For-each Loop for Java Array:
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type iterative_variable:array){
//body of the loop
}

Sample program:
class Testarray1{
public static void main(String args[]){
int arr[ ]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
[Link](i); } }
Passing Array to a Method in Java

• We can pass the java array to method so that we can reuse the same logic on any array.
• Let's see the simple example to get the minimum number of an array using a method.
Example: [Link]
Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to declare the array while passing
an array to the method.
Below Java Program to demonstrate the way of passing an anonymous array
to method.

Example: [Link]
Returning Array from the Method

We can also return an array from the method in Java.

Example: [Link]
Multidimensional Arrays
Multidimensional arrays (arrays of two or more dimensions) is an array of arrays
Two-Dimensional Arrays
• The simplest form of the multidimensional array is the two-dimensional array..
• A two-dimensional array can be thought of as creating a table of data, with the data
organized by row and column.
Syntax to Declare Multidimensional Array in Java

dataType[ ][ ] arrayRefVar; (or)


dataType arrayRefVar[ ][ ];

To declare a two-dimensional array, you must specify the size of both dimensions.
For example,
here table is declared to be a two-dimensional array of int with the size 10 by 20:
int[ ][ ] table = new int [10][20];
Example:
A two-dimensional array is loaded with the numbers 1
through 12.
In this example, table[0][0] will have the value 1,
table[0][1] the value 2, table[0][2]
the value 3, and so on. The value of table[2][3] will be
12.

Conceptually, the array will look like that shown below. Notice
how the data is organized into a tabular form.
Example program for dynamic input:
//Example for taking inputs taking dynamically:
import [Link].*; [Link]("Elements in Array are :\n");
class TwoDimensionalScanner for (int i = 0; i < row; i++)
{ {
public static void main(String args[]) for(int j = 0; j < column; j++)
{ {
[Link]("Row ["+i+"]: Column
Scanner sc=new Scanner([Link]); ["+j+"] :"+a[i][j]);
[Link]("Enter Row length of an array : "); }
int row=[Link](); }
[Link]("Enter column length of an array : "); }
int column=[Link](); }
int a[][]=new int[row][column];//declaration
[Link]("Enter " + row*column + " Elements to
Store in Array :\n");
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
{
a[i][j] = [Link]();
}
}
Addition Of Two Matrices:
class addtwomatrices
Program
{ Demonstrating
public static void main(String args[])
{
DD Array
int a[ ][ ]={{1,2,3},{4,5,6},{7,8,9}};
int b[ ][ ]={{1,1,1},{1,1,1},{1,1,1}};
int c[ ][ ]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j] =a[i][j]+b[i][j];
[Link](c[i][j]+" ");
}
[Link]();
}
}
}
Multiplication of two matrices :

public class MatrixMultiplicationExample{ for(int k=0;k<3;k++)


public static void main(String args[]){ {
//creating two matrices c[i][j]+=a[i][k]*b[k][j];
int a[][]={{1,1,1},{2,2,2},{3,3,3}}; }
int b[][]={{1,1,1},{2,2,2},{3,3,3}}; //end of k loop
Output:
//creating another matrix to store the multiplication of two matrices [Link](c[i][j]+" ");
666
//printing matrix element
int c[][]=new int[3][3]; //3 rows and 3 columns 12 12 12
}
//multiplying and printing multiplication of 2 matrices 18 18 18
//end of j loop
for(int i=0;i<3;i++){
[Link]();//new line
for(int j=0;j<3;j++){
}
c[i][j]=0;
}}
Irregular/Jagged Arrays
• It is an array of arrays with different number of columns.
• During the allocation of memory for a multidimensional array, you need to
specify only the memory for the first (leftmost) dimension.
• You can allocate the remaining dimensions separately.

• The use of irregular (or jagged) multidimensional arrays is not appropriate for all
situations.
• Often, a regular two-dimensional array is the best choice.
• However, irregular arrays can be quite effective in some situations.
• In general, if you need a very large two-dimensional array that is sparsely
populated (that is, one in which few of the elements will be used), an irregular
array might be a perfect solution.
Example for jagged/ Irreggular array :F:\CSE\JAVA\[Link]
Assigning Array References

when you assign one array reference variable to another,


• you are simply changing what object that variable refers to.
• You are not causing a copy of the array to be made,
• nor are you causing the contents of one array to be copied to the other.

This example
• creates two arrays and gives them initial values.
• Thus, at the start, nums1 and nums2 refer to separate and distinct arrays.
• Next, nums1 is assigned to nums2.
• After this assignment, both nums1 and nums2 now refer to the same array.
• Therefore, changing the array through nums2 (as the example does) also affects
the array referred to by nums1 because they both refer to the same array.
Collection

• In java, the Collection framework provides an architecture that stores and


manipulate the group of objects.
• To operate the group of objects we need to understand the Collection framework.
• The Collection framework can perform searching, sorting, insertion, manipulation,
and deletion operations as you perform on data.
• The group of objects behaves like a single unit in the Collection framework.
• A Collection framework provides some interfaces known as collection interfaces in
java and some classes known as collection classes in java.
Collection Framework
Array List:
An ArrayList class is a Resizable array, which is present in the java. util
package.
While built-in arrays have a fixed size, ArrayLists can change their size
dynamically.
Elements can be added and removed from an ArrayList whenever there
is a need, helping the user with memory management.
ArrayList in Java is used to store dynamically sized collection of
elements. Contrary to Arrays that are fixed in size, an ArrayList grows
its size automatically when new elements are added to it.
ArrayList is part of Java's collection framework and implements Java's
List interface. Syntax:
ArrayList<Object> Arrayname = new ArrayList<Object>();
Example:
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<String> str = new ArrayList<String>();
ArrayList Methods

ArrayList add: This is used to add elements to the Array List. If an ArrayList already contains
elements, the new element gets added after the last element unless the index is specified.
Syntax: add(Object o);

ArrayList remove: The specified element is removed from the list and the size is reduced
accordingly. Alternately, you can also specify the index of the element to be removed.
Syntax: remove(Object o);

Java array size: This will give you the number of elements in the Array List. Just like arrays, here
too the first element starts with index 0.
Syntax: int n = [Link]();

ArrayList contains: This method will return true if the list contains the specified element.
Syntax: boolean contains(Object o);
Add to an ArrayList
ArrayList<Integer> list = new ArrayList<Integer>();

[Link](5);
[Link](3);
[Link](10);
[Link](4);
Get a Value in an ArrayList
int val = [Link](1); //has value 3 Loop Over ArrayList
Set a Value in an ArrayList
for(int i = 0; i < [Link](); i++)
[Link](2,88); {
int element = [Link](i);
//use element
}
Length or Size of ArrayList
int length = list . size(); //length=4
Array List:
Syntax:
ArrayList<Object> Arrayname = new ArrayList<Object>();
Example:
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<String> str = new ArrayList<String>();

Example 1 Demonstrating add() method: F:\CSE\JAVA\[Link]


Example 2: Demonstrating Get(), Set() method: F:\CSE\JAVA\[Link]
Example 3: Demonstrating remove(), clear() method: F:\CSE\JAVA\[Link]
Example 4: Demonstrating Size() method: F:\CSE\JAVA\[Link]
Example 5: Demonstrating sort() method: F:\CSE\JAVA\[Link]
Vector Class:
Java Vector class comes under the [Link] package. The vector class
implements a growable array of objects. Like an array, it contains the
component that can be accessed using an integer index.

Vector is very useful if we don't know the size of an array in advance or we


need one that can change the size over the lifetime of a program.
Vector implements a dynamic array that means it can grow or shrink as
required. It is similar to the ArrayList, but with two differences.

The properties of vectors are as follows


Vector Class:
1)Vectors are Synchronized.
2)The vector contains many legacy methods that are not the part of a collections
framework
3)The vector is resizable
4)Duplicate objects are allowed.
5)Insertion order is preserved.
6)‘null’ insertion is possible.
7)Heterogeneous objects are allowed.
8)Vector class implements the Serializable, Cloneable and RandomAccess
interfaces
9)As most of the methods present in the Vector are Synchronized, the Vector
object is Thread-safe (where as arraylist is not thread-safe)
Synchronization in Vector

The vector is synchronized i.e. all the methods in Vector are marked ‘synchronized’ and thus
once a method is invoked, the same method cannot be invoked unless the previous call has
ended.
The vector class has many methods that are not a part of the collections framework but its
legacy methods.
A Vector is an array of objects or vector of objects.
Initialize Vector
(i) Vector()
This is the default constructor of the Vector class. When you invoke this constructor, a
Vector object of default size 10 is created.
The general syntax of this method is:
Vector object = new Vector();
For Example,
Vector vec1 = new Vector ();
The above statement creates a new Vector ‘vec1’ with size 10

(ii) Vector(int initialCapacity)


The overloaded constructor of the Vector class accepts ‘initialCapacity’ as the argument. This
constructor creates a Vector object with the specified capacity.
The general syntax of the method is:
Vector object = new Vector (initialCapacity);
For Example,
Vector vec1 = new Vector (10);
The above programming statement will create a Vector object ‘vec1’ with the capacity of 10 i.e.
this Vector can store up to 10 elements.
Example:1
import [Link].*; //Checking if Rat is present or not in this vector
public class vec { if([Link]("Rat"))
public static void main(String args[]) { {
[Link]("Rat is present at the index "
Vector<String> vec = new Vector<String>(4); +[Link]("Rat"));
[Link]("Tiger"); }
[Link]("Lion"); else
[Link]("Dog"); [Link]("Elephant"); {
[Link]("Rat is not present in the list.");
[Link]("Size is: "+[Link]()); }
[Link]("Default capacity is: "+[Link]()); //Get the first element
[Link]("Vector element is: "+vec); [Link]("The first animal of the vector is = "+[Link]());
[Link]("Rat"); //Get the last element
[Link]("The last animal of the vector is = "+[Link]());
[Link]("Cat"); }
[Link]("Deer"); }
[Link]("Size after addition: "+[Link]());
[Link]("Capacity after addition is: "+[Link]());
[Link]("Elements are: "+vec);
Example 2: size and capacity methods

F:\CSE\JAVA\[Link]
Example:3
import [Link];
public class VectorCapacityExample2 {
public static void main(String arg[]) {
//Create an empty Vector with an initial capacity of 3
Vector<String> vc = new Vector<>(3);
//Add elements in the vector
[Link]("A"); Output:
[Link]("B"); ABC
[Link]("C"); 3
//Print all the elements of a Vector A B C java
[Link]("Elements of Vector are: "+vc); 6
[Link]("Current capacity of Vector: "+[Link]());
//Add new element
[Link]("Java");
//After addition, print all the elements again
[Link]("Elements after addition: "+vc);
[Link]("Current capacity of Vector after modification: "+[Link]());
}
}
Example:4
import [Link];
public class VectorCapacityExample3 {
public static void main(String arg[]) {
//Create an empty Vector
Vector<String> vc = new Vector<>();
//Add elements in the vector
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("Default capacity of Vector: "+[Link]());
}
}

Output: 10
Vector vs Array
Enlisted below are some of the differences between a Vector and an Array.

Vector Array
Vector is dynamic and its size grows and Arrays are static and its size remains fixed
shrinks as elements are added or removed. once declared.
Vectors can store only objects. Arrays can store primitive types as well as
objects.
It provides a size() method to determine the Provides length property to determine the
size. length.
No concept dimensions but can be created as Arrays support dimensions.
a vector of vectors, normally called 2d vector.

Vector is synchronized. The array is not synchronized.


Vector is slower than the array. Array is faster.
Reserves additional storage when capacity is Does not reserve any additional storage.
incremented.
Ensures type safety by supporting generics. No generic support.
Vector vs ArrayList
Enlisted below are some of the differences between a Vector and an Array.

ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

ArrayList increments 50% of current Vector increments 100% means doubles the array
array size if the number of elements size if the total number of elements exceeds than its
exceeds from its capacity. capacity.
3) ArrayList is not a legacy class. It is Vector is a legacy class.
introduced in JDK 1.2.
4) ArrayList is fast because it is non- Vector is slow because it is synchronized, i.e., in a
synchronized. multithreading environment, it holds the other
threads in runnable or non-runnable state until
current thread releases the lock of the object.
5) ArrayList uses the Iterator interface A Vector can use the Iterator interface
to traverse the elements. or Enumeration interface to traverse the elements.
Thank You

CSE, GST, VISAKHAPATNAM

You might also like