Arrays and Strings
Array • An array is an object which contains elements of a similar data type. • The elements of an array are stored in a contiguous memory location. • In java, all arrays are dynamically allocated. • Size of an array can be retrieved by using length function. • Each item in an array is called an element, and each element is accessed by its numerical index. • ava arrays enable you to access any element randomly with the help of indexes
Types of Arrays • One-Dimensional Arrays • N-dimensional Arrays • Multidimensional Arrays • Irregular/Jagged Arrays
One-Dimensional Arrays A one-dimensional array is, essentially, a list of similar-typed values. Syntax type variable_name[ ]; or type[] variable_name; Example int student_roll[]; or int[] student_roll; student_roll = new int[12];
Different ways of initializing array int student_roll[] = new int[4]; student_roll[0]=100; student_roll[1]=101; student_roll[3]=102; student_roll[4]=103; int student_roll[] = {100, 101, 102, 103}; int student_roll[] = new int[]{100, 101, 102, 103};
// Average an array of values. class Average { public static void main(String args[]) { double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5}; double result = 0; int i; for(i=0; i<nums.length; i++) result = result + nums[i]; System.out.println("Average is " + (result / 5)); } }
Multidimensional Arrays In Java, multidimensional arrays are actually arrays of arrays. int twoD[][] = new int[4][5];
// Demonstrate a two-dimensional array. class TwoDArray { public static void main(String args[]) { int twoD[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } }
Irregular Arrays/Jagged Arrays • Irregular arrays are a kind of n-dimensional (n>1) arrays, which are represented as arrays of one-dimensional arrays with different numbers of elements (items). • In an irregular array, the size of one-dimensional arrays, which corresponds to the last dimension, is various. • Memory for such one-dimensional arrays is allocated of different sizes.
int[][] A = new int[3][5]; // regular array int[][] B = new int[3][]; // irregular two-dimensional array int[][][] C = new int[3][4][]; // irregular three-dimensional array int[][][] D = new int[3][][]; // irregular three-dimensional array int[][][] E = new int[][][]; // error
public class JaggedDemo { public static void main(String args[]){ int[][] arr = new int[2][]; //first row has 3 columns arr[0] = new int[3]; //second row has 4 columns arr[1] = new int[4]; int counter = 0; //initializing array for(int i=0; i < arr.length; i++){ for(int j=0; j < arr[i].length; j++){ arr[i][j] = counter++; } } //printing array for(int i=0; i < arr.length; i++){ System.out.println(); for(int j=0; j < arr[i].length; j++){ System.out.print(arr[i][j] + " "); } } } }
Array References class ArrayDemo{ public static void main(String args[]) { int arr1[] = new int[10]; int arr2[] = new int[10]; int i; System.out.println("Entering arr1 elements:"); for(i=0; i<10;i++){ arr1[i]=i; } System.out.println("Entering arr2 elements:"); for(i=0; i<10;i++){ arr2[i]=-i; } System.out.println("Array 1 elements are:"); for(i=1; i<10;i++){ System.out.println(arr1[i]); } System.out.println("Array 2 elements are:"); for(i=0; i<10;i++){ System.out.println(arr2[i]); } arr2=arr1; System.out.println("Array 2 elements are:"); for(i=0; i<10;i++){ System.out.println(arr2[i]); } arr2[3]=50; System.out.println("Array 1 elements are:"); for(i=0; i<10;i++){ System.out.println(arr1[i]); } } }
Using the Length Member length is an instance variable of an array object that contains size of the array/ number of elements that the array can hold. class ArrayDemo{ public static void main(String args[]) { int arr1[] = new int[10]; int arr2[] = new int[10]; int i; System.out.println("Entering arr1 elements:"); for(i=0; i<arr1.length;i++){ arr1[i]=i; } System.out.println("Array 1 elements are:"); for(i=1; i<arr1.length;i++){ System.out.println(arr1[i]); } } }
Arrays class of util package • Array class in java.util package provides static methods to dynamically create and access java arrays. • The methods in the Array class are used mostly for the manipulation of an array including all major operations like creating, sorting, searching comparing, etc.
• java.util.Arrays class provides lot's of methods here, the frequently used and important Arrays class methods are as follows, static int binarySearch(int[] a, int key) - Searches the specified array of ints for the specified value using the binary search algorithm. static boolean deepEquals(Object[] a1, Object[] a2) - Returns true if the two specified arrays are deeply equal to one another. static void fill(int[] a, int val) - Assigns the specified int value to each element of the specified array of ints. static void sort(int[] a) - Sorts the specified array into ascending numerical order. static int[] copyOf(int[] original, int newLength) - Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. static String toString(int[] a) - Returns a string representation of the contents of the specified array.
Example program import java.util.Arrays; public class Scaler { public static void main(String[] args) { int Arr[] = { 10, 20, 11, 21, 31 }; Arrays.sort(Arr); int Key = 31; System.out.println( Key + " found at index = " + Arrays.binarySearch(Arr, Key)); } }
ArrayList • Java ArrayList class uses a dynamic array for storing the elements. • It is like an array, but there is no size limit. • We can add or remove elements anytime. So, it is much more flexible than the traditional array. • It is found in the java.util package. • We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class. • Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies according to the elements getting added or removed from the list.
Important methods of ArrayList void add(int index, E element): It is used to insert the specified element at the specified position in a list. void clear(): It is used to remove all of the elements from this list. boolean remove(Object o): It is used to remove the first occurrence of the specified element. int size(): It is used to return the number of elements present in the list. List<E> subList(int fromIndex, int toIndex): It is used to fetch all the elements that lies within the given range. void sort(Comparator<? super E> c): It is used to sort the elements of the list on the basis of the specified comparator. E set(int index, E element): It is used to replace the specified element in the list, present at the specified position. int indexOf(Object o): It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
Example Programs import java.util.*; public class ArrayListExample1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); //Creating arraylist list.add("Mango");//Adding object in arraylist list.add("Apple"); list.add("Banana"); list.add("Grapes"); //Printing the arraylist object System.out.println(list); } }
import java.util.*; public class ArrayListExample4{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Mango"); al.add("Apple"); al.add("Banana"); al.add("Grapes"); //accessing the element System.out.println("Returning element: "+al.get(1)); //changing the element al.set(1,"Dates"); //Traversing list for(String fruit:al) System.out.println(fruit); } }
Vector Class • Vector is like the dynamic array variable size. • Java Vector contains many legacy methods. • Vector class works better if there is a thread-safe implementation. Important methods of vector class add(): It is used to append the specified element in the given vector. addAll(): It is used to append all of the elements in the specified collection to the end of this Vector. addElement(): It is used to append the specified component to the end of this vector. It increases the vector size by one. capacity(): It is used to get the current capacity of this vector.
clear(): It is used to delete all of the elements from this vector. clone(): It returns a clone of this vector. contains(): It returns true if the vector contains the specified element. copyInto(): It is used to copy the components of the vector into the specified array. elementAt(): It is used to get the component at the specified index. equals(): It is used to compare the specified object with the vector for equality. get(): It is used to get an element at the specified position in the vector. isEmpty(): It is used to check if this vector has no components. iterator(): It is used to get an iterator over the elements in the list in proper sequence. remove(): It is used to remove the specified element from the vector. If the vector does not contain the element, it is unchanged. set(): It is used to replace the element at the specified position in the vector with the specified element. size(): It is used to get the number of components in the given vector. sort(): It is used to sort the list according to the order induced by the specified Comparator. toString(): It is used to get a string representation of the vector.
import java.util.*; public class VectorExample2 { public static void main(String args[]) { //Create an empty Vector Vector<Integer> in = new Vector<>(); //Add elements in the vector in.add(100); in.add(200); in.add(300); in.add(200); in.add(400); in.add(500); in.add(600); in.add(700); //Display the vector elements System.out.println("Values in vector: " +in); //Remove the element at index 4 System.out.println("Remove element at index 4: " +in.remove(4)); System.out.println("New Value list in vector: " +in); //Get the element at specified index System.out.println("Element at index 1 is = "+in.get(1)); } }

Arrays and Strings engineering education

  • 1.
  • 2.
    Array • An arrayis an object which contains elements of a similar data type. • The elements of an array are stored in a contiguous memory location. • In java, all arrays are dynamically allocated. • Size of an array can be retrieved by using length function. • Each item in an array is called an element, and each element is accessed by its numerical index. • ava arrays enable you to access any element randomly with the help of indexes
  • 3.
    Types of Arrays •One-Dimensional Arrays • N-dimensional Arrays • Multidimensional Arrays • Irregular/Jagged Arrays
  • 4.
    One-Dimensional Arrays A one-dimensionalarray is, essentially, a list of similar-typed values. Syntax type variable_name[ ]; or type[] variable_name; Example int student_roll[]; or int[] student_roll; student_roll = new int[12];
  • 5.
    Different ways ofinitializing array int student_roll[] = new int[4]; student_roll[0]=100; student_roll[1]=101; student_roll[3]=102; student_roll[4]=103; int student_roll[] = {100, 101, 102, 103}; int student_roll[] = new int[]{100, 101, 102, 103};
  • 6.
    // Average anarray of values. class Average { public static void main(String args[]) { double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5}; double result = 0; int i; for(i=0; i<nums.length; i++) result = result + nums[i]; System.out.println("Average is " + (result / 5)); } }
  • 7.
    Multidimensional Arrays In Java,multidimensional arrays are actually arrays of arrays. int twoD[][] = new int[4][5];
  • 8.
    // Demonstrate atwo-dimensional array. class TwoDArray { public static void main(String args[]) { int twoD[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } }
  • 9.
    Irregular Arrays/Jagged Arrays •Irregular arrays are a kind of n-dimensional (n>1) arrays, which are represented as arrays of one-dimensional arrays with different numbers of elements (items). • In an irregular array, the size of one-dimensional arrays, which corresponds to the last dimension, is various. • Memory for such one-dimensional arrays is allocated of different sizes.
  • 10.
    int[][] A =new int[3][5]; // regular array int[][] B = new int[3][]; // irregular two-dimensional array int[][][] C = new int[3][4][]; // irregular three-dimensional array int[][][] D = new int[3][][]; // irregular three-dimensional array int[][][] E = new int[][][]; // error
  • 11.
    public class JaggedDemo{ public static void main(String args[]){ int[][] arr = new int[2][]; //first row has 3 columns arr[0] = new int[3]; //second row has 4 columns arr[1] = new int[4]; int counter = 0; //initializing array for(int i=0; i < arr.length; i++){ for(int j=0; j < arr[i].length; j++){ arr[i][j] = counter++; } } //printing array for(int i=0; i < arr.length; i++){ System.out.println(); for(int j=0; j < arr[i].length; j++){ System.out.print(arr[i][j] + " "); } } } }
  • 12.
    Array References class ArrayDemo{ publicstatic void main(String args[]) { int arr1[] = new int[10]; int arr2[] = new int[10]; int i; System.out.println("Entering arr1 elements:"); for(i=0; i<10;i++){ arr1[i]=i; } System.out.println("Entering arr2 elements:"); for(i=0; i<10;i++){ arr2[i]=-i; } System.out.println("Array 1 elements are:"); for(i=1; i<10;i++){ System.out.println(arr1[i]); } System.out.println("Array 2 elements are:"); for(i=0; i<10;i++){ System.out.println(arr2[i]); } arr2=arr1; System.out.println("Array 2 elements are:"); for(i=0; i<10;i++){ System.out.println(arr2[i]); } arr2[3]=50; System.out.println("Array 1 elements are:"); for(i=0; i<10;i++){ System.out.println(arr1[i]); } } }
  • 13.
    Using the LengthMember length is an instance variable of an array object that contains size of the array/ number of elements that the array can hold. class ArrayDemo{ public static void main(String args[]) { int arr1[] = new int[10]; int arr2[] = new int[10]; int i; System.out.println("Entering arr1 elements:"); for(i=0; i<arr1.length;i++){ arr1[i]=i; } System.out.println("Array 1 elements are:"); for(i=1; i<arr1.length;i++){ System.out.println(arr1[i]); } } }
  • 14.
    Arrays class ofutil package • Array class in java.util package provides static methods to dynamically create and access java arrays. • The methods in the Array class are used mostly for the manipulation of an array including all major operations like creating, sorting, searching comparing, etc.
  • 15.
    • java.util.Arrays classprovides lot's of methods here, the frequently used and important Arrays class methods are as follows, static int binarySearch(int[] a, int key) - Searches the specified array of ints for the specified value using the binary search algorithm. static boolean deepEquals(Object[] a1, Object[] a2) - Returns true if the two specified arrays are deeply equal to one another. static void fill(int[] a, int val) - Assigns the specified int value to each element of the specified array of ints. static void sort(int[] a) - Sorts the specified array into ascending numerical order. static int[] copyOf(int[] original, int newLength) - Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. static String toString(int[] a) - Returns a string representation of the contents of the specified array.
  • 16.
    Example program import java.util.Arrays; publicclass Scaler { public static void main(String[] args) { int Arr[] = { 10, 20, 11, 21, 31 }; Arrays.sort(Arr); int Key = 31; System.out.println( Key + " found at index = " + Arrays.binarySearch(Arr, Key)); } }
  • 17.
    ArrayList • Java ArrayListclass uses a dynamic array for storing the elements. • It is like an array, but there is no size limit. • We can add or remove elements anytime. So, it is much more flexible than the traditional array. • It is found in the java.util package. • We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class. • Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies according to the elements getting added or removed from the list.
  • 18.
    Important methods ofArrayList void add(int index, E element): It is used to insert the specified element at the specified position in a list. void clear(): It is used to remove all of the elements from this list. boolean remove(Object o): It is used to remove the first occurrence of the specified element. int size(): It is used to return the number of elements present in the list. List<E> subList(int fromIndex, int toIndex): It is used to fetch all the elements that lies within the given range. void sort(Comparator<? super E> c): It is used to sort the elements of the list on the basis of the specified comparator. E set(int index, E element): It is used to replace the specified element in the list, present at the specified position. int indexOf(Object o): It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
  • 19.
    Example Programs import java.util.*; publicclass ArrayListExample1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); //Creating arraylist list.add("Mango");//Adding object in arraylist list.add("Apple"); list.add("Banana"); list.add("Grapes"); //Printing the arraylist object System.out.println(list); } }
  • 20.
    import java.util.*; public classArrayListExample4{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Mango"); al.add("Apple"); al.add("Banana"); al.add("Grapes"); //accessing the element System.out.println("Returning element: "+al.get(1)); //changing the element al.set(1,"Dates"); //Traversing list for(String fruit:al) System.out.println(fruit); } }
  • 21.
    Vector Class • Vectoris like the dynamic array variable size. • Java Vector contains many legacy methods. • Vector class works better if there is a thread-safe implementation. Important methods of vector class add(): It is used to append the specified element in the given vector. addAll(): It is used to append all of the elements in the specified collection to the end of this Vector. addElement(): It is used to append the specified component to the end of this vector. It increases the vector size by one. capacity(): It is used to get the current capacity of this vector.
  • 22.
    clear(): It isused to delete all of the elements from this vector. clone(): It returns a clone of this vector. contains(): It returns true if the vector contains the specified element. copyInto(): It is used to copy the components of the vector into the specified array. elementAt(): It is used to get the component at the specified index. equals(): It is used to compare the specified object with the vector for equality. get(): It is used to get an element at the specified position in the vector. isEmpty(): It is used to check if this vector has no components. iterator(): It is used to get an iterator over the elements in the list in proper sequence. remove(): It is used to remove the specified element from the vector. If the vector does not contain the element, it is unchanged. set(): It is used to replace the element at the specified position in the vector with the specified element. size(): It is used to get the number of components in the given vector. sort(): It is used to sort the list according to the order induced by the specified Comparator. toString(): It is used to get a string representation of the vector.
  • 23.
    import java.util.*; public classVectorExample2 { public static void main(String args[]) { //Create an empty Vector Vector<Integer> in = new Vector<>(); //Add elements in the vector in.add(100); in.add(200); in.add(300); in.add(200); in.add(400); in.add(500); in.add(600); in.add(700); //Display the vector elements System.out.println("Values in vector: " +in); //Remove the element at index 4 System.out.println("Remove element at index 4: " +in.remove(4)); System.out.println("New Value list in vector: " +in); //Get the element at specified index System.out.println("Element at index 1 is = "+in.get(1)); } }