Java Tutorial

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java BufferedWriter Java InputStreamReader Java File Java Read File Line By Line Java FileOutputStream Jar File in Java

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial

Java Differences

Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Static vs Non-static in Java C vs Java int vs Integer in Java Stack vs Heap in Java Java Array vs ArrayList

How to

How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to call a method in Java How to sort an array in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to achieve abstraction in Java How to call static method in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Parallel Arrays Sort in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hibernate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java Convert Char array to string in java Check whether Java is installed or not How to calculate time difference in Java How to stop execution after a certain time in Java Jagged Array in Java Java ArraylistRemove() Time Complexity Java Swing Time Picker Zigzag Array in Java

Java ArrayList

Java ArrayList Class

A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the AbstractList class.

The benefit of using ArrayList over a standard array is that, in a standard array, we are able to store only a fixed number of elements. Java ArrayList also allows us to access the list randomly.

Java ArrayList comprises of both constructors and methods. Following are some constructors and methods along with their usage.

Constructors of ArrayList :

ArrayList() It creates an empty ArrayList with a default capacity of 10. Syntax: ArrayList<E> myArray= new ArrayList<E>();
ArrayList(Collection c) It creates a list containing the elements of the specified collection. Syntax: public boolean addAll(collection c)
ArrayList(int Capacity) It creates an empty ArrayList of specified capacity in the parameter. Syntax: ArrayList myArray= new ArrayList(int Capacity);

Example to use constructors:

import java.util.*;
public class Constructor 
 {
 public static void main(String args[])
  {
  //first create ArrayList of type string 
  ArrayList>String> a= new ArrayList>String>();
  int counter=0;
  for (String s:a)
  {
  counter++; 
  }
  System.out.println("No Arguments:"+counter);
 //we don't have any element in the ArrayList, so when we try to print the counter value it will not retain any value.
 //we will create one more ArrayList and initialize the capacity to that.
  ArrayList>String> b=new ArrayList>String>(20); 
   counter=0;
  for (String s:a)
  {
  counter++;
  }
  System.out.println("No Arguments with capacity:"+counter); 
   System.out.println();
  //If we try to print the counter it won't print because we initialize capacity and also the value of the counter will not increase.
  //Now, again we create the ArrayList with the elements
  String sArray[]= {"Java", "Android", "Kotlin", "Python"};
  List list= Arrays.asList(sArray);
  ArrayList c=new ArrayList(list); 
  c.add("PL/SQL");//it will append the element to the list
  //using advance for loop
  for(String s:c)
  System.out.println("ArrayList c element"+s);
  System.out.println(c); 

Output:

No Arguments:0
No Arguments with capacity:0
ArrayList c element :Java
ArrayList c element :Android
ArrayList c element :Kotlin
ArrayList c element :Python 
ArrayList c element :PL/SQL
[Java, Android, Kotlin, Python, PL/SQL] 

Methods of Java ArrayList:

Modifier And Type Methods Usage
Boolean add (E a) It is used to add an element to the end of the list
addAll(Collection c) It is used to add all of the elements in the specified collection to the end of the list. And it is added in the order that they returned from the specified collection's iterator.
addAll(int index, Collection c) It will insert all the elements at the specified index position in the specified collection into the list.
Contains(Object o) If the list contains the specified elements, it will return true.
isEmpty() If the list is blank, it will return true.
remove(Object o) If the specified element is present, then the first occurrence of that element will be removed from the list.
removeAll(Collection c) It will remove all the elements of the list from the specified collection.
retainAll(Collection c) It continues to hold only the elements in the list contained in the specified collection.
int indexof(Object o) It will return -1 if the list is blank or returns the index number for the first occurrence of the specified component in the list.
lastIndexOf(Object o) It will return the index of the last occurrence of the specified element in the list, or -1 if the list is empty.
size() It gives the number of elements in the list.
void add(int index, E element) It is used to insert a specific element at the specified position in the ArrayList.
clear() It will remove all elements from the list.
ensureCapacity(int minCapacity) The capacity of the ArrayList will be increased to ensure that it holds the minimum number of elements specified in the minCapacity argument.
trimToSize() It will trim the capacity of the ArrayList to the list's current size.
Object[ ] clone() It will return a shallow copy of the ArrayList instance.
toArray() Will return an array containing all elements in the list in proper sequence(First to Last).
Iterator<E> iterator() It will return an iterator over the element in the list in the sequence.
ListIterator<E> listIterator() Will return a listIterator over the element in the list(in sequence)
listIterator(int index) Will return a listIterator over the element in the list from the specified index.
List<E> subList(int fromIndex, int toIndex) Returns the element from the list between the specified index value.
abstract<E> get(int index) It will return the element from the specified index in the list.
E remove(int index) It removes the element from the specified position in the list.
E set(int index, E element) It will replace the element from the specified position in the list with the specified element in the argument.

Advantages of ArrayList over Array:

  • The length of the ArrayList is variable.
  • The size of the ArrayList can be modified dynamically.
  • The ArrayList can traverse in both directions.
  • We can add different types of data in an ArrayList if we do not use generics.

Example to add, remove, clone, and clear the elements in the ArrayList.

import java.util.ArrayList;
 public class Arraylist {
        public static void main(String[] args) 
        {
               // we will see how to add elements 
               ArrayList al=new ArrayList();
               Object cloneList;
               al.add("Android");
               al.add("Java");
               al.add("Arrays"); 
               System.out.println("Size of arraylist:"+ al.size());//It will show the size               of the array
               System.out.println("Content of al:"+al);//It will show the contents of the array
               al.remove("Java");//It will remove java from the list
               System.out.println("Size of arraylist after deletion:"+al.size()); 
               System.out.println("Content of al:"+al);//prints content after deletion
               cloneList=al.clone();//It will clone the present element in the list
               System.out.println("Elements in the cloned list are:"+cloneList);
               al.clear();//It will clear the ArrayList
               System.out.println("Arraylist after clear:"+al);
        }
 } 

Output:

Size of arraylist:3
Content of al:[Android, Java, Arrays]
Size of arraylist after deletion:2
Content of al:[Android, Arrays]
Elements in the cloned list are:[Android, Arrays]
Arraylist after clear:[] 

Example to illustrate addAll(Collection c)

import java.util.*;
 import java.io.*;
 class ArrayListDemo
 {
     public static void main (String[] args)
     {
       //Creating an empty array list1 
       ArrayList<String> arrlist1 = new ArrayList<String>(5);//capacity=5
       //now using add method to add elements in the list
        arrlist1.add("Java");
        arrlist1.add("Python");
        arrlist1.add("Hadoop"); 
        // It prints all the elements available in list1
        System.out.println("Printing list1:");
        for (String subject : arrlist1)  
              System.out.println("Subjects = " + subject);          
        // creating another empty array list2 
        ArrayList<String> arrlist2 = new ArrayList<String>(5);
        //add() method to add elements in list2
        arrlist2.add("Android");
        arrlist2.add("CPP"); 
        arrlist2.add("R programming");
        arrlist2.add("CCNA");
        //Printing all the elements available in list2
        System.out.println("Printing list2:");
        for (String subject : arrlist2)   
         System.out.println("Subjects = " + subject);        
        // inserting all elements then list 2 will get printed after list 1
        arrlist1.addAll(arrlist2);
        System.out.println("Printing all the elements");
        //Printing all the elements available in list1   
        for (String subject : arrlist1)   
              System.out.println("Subjects = " + subject);
     }
 } 

Output:

Printing list1:
Subjects = Java
Subjects = Python
Subjects = Hadoop
Printing list2: 
Subjects = Android
Subjects = CPP
Subjects = R programming
Subjects = CCNA
Printing all the elements
Subjects = Java
Subjects = Python
Subjects = Hadoop
Subjects = Android
Subjects = CPP
Subjects = R programming
Subjects = CCNA 

Example to illustrate addAll(int index, Collection c)

import java.io.*;
 import java.util.*;
    class ArrayListdemo {
        public static void main(String args[])
        {
        // creating an empty array list1 
        ArrayList<String> arrlist1 = new ArrayList<String>(5);//capacity 5
        //To add elements in the list,using add() method
        arrlist1.add("Jammu and Kashmir");
        arrlist1.add("Himachal Pradesh");
        arrlist1.add("Punjab"); 
        // prints all the elements available in list1
        System.out.println("Printing list1:");
        for (String state : arrlist1)
              System.out.println("State = " + state);         
        // creating an empty array list2
        ArrayList<String> arrlist2 = new ArrayList<String>(5);//capacity 5
        //To add elements in list2, using add() method
        arrlist2.add("Delhi"); 
        arrlist2.add("UP");
        arrlist2.add("Bihar");
        arrlist2.add("Gujarat");
        // prints all the elements available in list2 
        System.out.println("Printing list2:");
        for (String state : arrlist2)
              System.out.println("State = " + state);        
        // inserting all elements of list2 at fourth position 
        arrlist1.addAll(3, arrlist2);
        System.out.println("Printing all the elements");
        // prints all the elements available in list1
        for (String state : arrlist1) 
              System.out.println("State = " + state);        
        }
 } 

Output:

Printing list1:
State = Jammu and Kashmir
State = Himachal Pradesh
State = Punjab
Printing list2: 
State = Delhi
State = UP
State = Bihar
State = Gujarat 
Printing all the elements
State = Jammu and Kashmir
State = Himachal Pradesh
State = Punjab 
State = Delhi
State = UP
State = Bihar
State = Gujarat 

Example to demonstrate the working of contains() method in ArrayList.

import java.util.*;
 class StudentContains {
        public static void main(String[] args)
        {
        // creating an Empty String ArrayList
        ArrayList<String> arr = new ArrayList<String>(5);//Capacity 5 
        // using add() method to initialize values
        arr.add("Ankit");
        arr.add("Aman");
        arr.add("Vikash");
        arr.add("Himanshu"); 
        arr.add("Anubhav");
        // using contains() to check if the student Aman is present or not
        boolean ans = arr.contains("Aman");
        if (ans)
              System.out.println("Student Aman is present");
        else 
              System.out.println("Aman is not present");
        // using contains() to check if Anubhav is present or not.
        ans = arr.contains("Akshay");
        if (ans) 
              System.out.println(" Akshay is present");
        else
              System.out.println("Anubhav is not present");
        }
 } 

Output :

Student Aman is present
Anubhav is not present 

Example to demonstrate the working of isEmpty() method in ArrayList

import java.util.*;
 class CheckEmpty {
        public static void main(String[] args)
        {
        // creating an Empty ArrayList
        ArrayList<String> arr = new ArrayList<String>(20); 
        // checking, list is empty or not
        boolean ans = arr.isEmpty();
        if (ans == true)
              System.out.println("The ArrayList is empty");
        else
              System.out.println("The ArrayList is not empty"); 
        // adding an element to the ArrayList
        arr.add("Tutorials And Example");
        // checking, list is empty or not
        ans = arr.isEmpty();
        if (ans == true)
              System.out.println("The ArrayList is empty"); 
        else
              System.out.println("The ArrayList is not empty");
        }
 } 

Output:

The ArrayList is empty
The ArrayList is not empty 

Example to demonstrate the working of indexOf in ArrayList

import java.util.*;
class IndexOfExample {
public static void main(String[] args) {
 // creating an Empty Integer ArrayList
ArrayList<Integer> roll = new ArrayList<Integer>(10); 
 // using add() to initialize and add values
 roll.add(1);
 roll.add(2);
 roll.add(3);
 roll.add(4);
 roll.add(5); 
  roll.add(6);
  // printing initial value of ArrayList
  System.out.print("The initial values in ArrayList are : ");
  for (Integer value : roll) {
  System.out.print(value); 
  System.out.print("  ");
  }   
  // using indexOf() to find index of 4
  int position =roll.indexOf(4);
  //printing index of element 4
  System.out.println("\nThe no. 4 is at index : " + position); 
  }
 }

Output:

The initial values in ArrayList are : 1 2 3 4 5 6
The element 4 is at index : 3 

Example to demonstrate the working of  lastIndexOf() and size() method in ArrayList.

import java.util.*;
 class LastIndexExample {
                 public static void main(String[] args)
                 {
                 // creating an Empty ArrayList
                 ArrayList<String> ar = new ArrayList<String>(10);
                 // using add() to initialize values 
                 ar.add("A");
                 ar.add("A");
                 ar.add("B");
                 ar.add("C");
                 ar.add("D");
                 ar.add("A"); 
                 ar.add("K");
                 ar.add("B");
                 ar.add("A");
                 ar.add("K");
                 System.out.println("The list initially " + ar);
                 int size = ar.size(); 
 // printing the size of array list
                System.out.println("Size of list = " + size);
                 // printing last index of A
                 int element = ar.lastIndexOf("A");
                 if (element != -1)
                System.out.println("the lastIndexof of A is " + element);   
                 else
                System.out.println("A is not present in the list");
                 // printing last index of B
                 element = ar.lastIndexOf("B");
                 if (element != -1)
                System.out.println("The lastIndexof of B is" + element); 
                 else
                System.out.println("B is not present in the list");
                  }
 } 

Output:

The list initially [A, A, B, C, D, A, K, B, A, K]
Size of list = 10
the lastIndexof of A is 8
The lastIndexof of B is7 

Example to illustrate add(int index, Object element):

import java.io.*;
import java.util.*;
class ArrayListExample {
public static void main(String[] args)
                {
                // Initializing an empty array list
                ArrayList<Integer> arlist = new ArrayList<Integer>(5); 
                 // using add() to add elements in the list
                 arlist.add(10);
                 arlist.add(5);
                 arlist.add(15);
                 // adding element 50 at 1st position
                 arlist.add(0, 50);
                 // printing all the elements available in list 
                 for (Integer num : arlist) {
                System.out.println("No. = " + num);
                 }
                 }
 } 

Output:

No. = 50
No. = 10
No. = 5
No. = 15 

Example to demonstrate  ensureCapacity() method:

import java.util.*;
 class CapacityDemo {
                 public static void main(String[] args) throws Exception
                 {
                 try {
                // Initializing object of ArrayList<Integer>
                ArrayList<String> arlist = new ArrayList<String>(); 
                // add element to array list
                arlist.add("A");
                arlist.add("B");
                arlist.add("C");
                arlist.add("D");
                // Printing the ArrayList
                System.out.println("ArrayList: "+ arlist); 
                // ensure that the ArrayList can hold upto 200 elements using ensureCapacity() method
                arlist.ensureCapacity(200);
                // Prints
                System.out.println("ArrayList can store upto 200 elements.");                      
                 }
                 catch (NullPointerException e) { 
                System.out.println("Exception : " + e);
                 }
                 }
 } 

Output:

ArrayList: [A, B, C, D]
ArrayList can store upto 200 elements. 

Example to demonstrate the working of  trimTosize() method in ArrayList.

import java.util.*;
 class trimExamp {
                 public static void main(String[] args)
                 {
                 // creating an Empty ArrayList
                 ArrayList<Integer> ar = new ArrayList<Integer>(10);
                 // using add() to add values 
                 ar.add(20);
                 ar.add(11);
                 ar.add(8);
                 ar.add(60);
                 ar.add(25);
                 // trims the size of array to the number of elements 
                 ar.trimToSize();
                 int size = ar.size();
                 // printing the size of array list
                System.out.println("Size of list = " + size);
                 System.out.println("Numbers in the list are:");
                 // printing all the elements
                 for (Integer num : ar) { 
                System.out.println("Number = " + num);
                 }
                 }
 } 

Output:

Size of list = 5
Numbers in the list are:
Number = 20
Number = 11
Number = 8
Number = 60
Number = 25 

Example to demonstrate working of Objectp[] toArray().

import java.io.*;
 import java.util.*;
 class ToArrayDemo
 {
                 public static void main (String[] args)
                 {
                 //initializing array list 
                 List<Integer> li = new ArrayList<Integer>();
                 li.add(1);
                 li.add(2);
                 li.add(3);
                 li.add(4); 
                 Object[] objects = li.toArray();
                 // Prints array of objects
                 for (Object obj : objects)
                System.out.print(obj + " ");
                 }
 } 

Output:

1 2 3 4

Example to demonstrate listIterator() method

import java.util.*;
 class ListIteratorDemo {
                 public static void main(String[] args) throws Exception
                 {
                 try {
                // Creating object of ArrayList<String>
                ArrayList<String> arlist = new ArrayList<String>();
                //now adding elements to the ArrayList
                arlist.add("Java");
                arlist.add("Spring");
                arlist.add("Boot");
                arlist.add("Hibernate");
                // Printing ArrayList
                System.out.println("ArrayList: "+ arlist);
                // Creating object of ListIterator
                // now using listIterator() method
                ListIterator<String> iterator = arlist.listIterator();
                // Printing the iterated values 
                System.out.println("\nUsing ListIterator:\n");
                while (iterator.hasNext()) {
                System.out.println("Value is : "+ iterator.next());
                }
                 }
                 catch (NullPointerException e) { 
                System.out.println("Exception thrown : " + e);
                 }
                 }
 } 

Output:

ArrayList: [Java, Spring, Boot, Hibernate]
Using ListIterator:
Value is : Java
Value is : Spring 
Value is : Boot
Value is : Hibernate 

Example to demonstrate subList() method

import java.util.*;
 class sublistDemo {
                 public static void main(String[] args) throws Exception
                 {
                 try {
                // Creating object of ArrayList 
                ArrayList<String> arlist = new ArrayList<String>();
                // adding elements to arlist1
                arlist.add("Java");
                arlist.add("Python");
                arlist.add("Android"); 
                arlist.add("IOS");
                arlist.add("IOT");
                // printing ArrayList
                System.out.println("Original arraylist: "+ arlist);
                // getting the subList using subList() method
                List<String> arlist2 = arlist.subList(2, 4);
                // printing the subList 
                System.out.println("Sublist of arraylist: "+ arlist2);
                 }
                 catch (IndexOutOfBoundsException e) {
                System.out.println("Exception : " + e);
                 } 
                 catch (IllegalArgumentException e) {
                System.out.println("Exception : " + e);
                 }
                 }
 } 

Output:

Original arraylist: [Java, Python, Android, IOS, IOT]
 Sublist of arraylist: [Android, IOS] 

Example to demonstrate the working of  get() method in ArrayList

import java.util.*;
                 class GetDemo
                 {
                 public static void main(String[] args)
                 {
                 // creating an Empty Integer ArrayList
                 ArrayList<Integer> num = new ArrayList<Integer>(4);
                 // using add() method to initialize values 
                 num.add(5);
                 num.add(2);
                 num.add(9);
                 num.add(1);
                 System.out.println("List: " + num); 
                 //using get() to fetch element from index 2    
                 int element = num.get(3);
                 System.out.println("Element at index 3 is " + element);
                 }
 } 

Output:

List: [5, 2, 9, 1]
Element at index 3 is 1 

Example to demonstrate set() method

import java.util.*;
class SetExample {
                public static void main(String[] args) throws Exception
                {
                try {
               // Creating object of ArrayList<Integer> 
                ArrayList<String> arrlist = new ArrayList<String>();
                // adding elements to arraylist
                arrlist.add("Java");
                arrlist.add("Spring");
                arrlist.add("Struts");
                arrlist.add("MongoDB");
                arrlist.add("Oracle"); 
                // printings ArrayList
                System.out.println("Before operation: "+ arrlist);
                // Replacing element at the index 3 with Hibernate using set()
                String i = arrlist.set(3, "Hibernate");
                // Print the modified arrlist
                System.out.println("After operation: "+ arrlist);
                // Print the Replaced element
                System.out.println("Replaced element: "  + i);                       
                 }
                 catch (IndexOutOfBoundsException e) {
                System.out.println("Exception thrown: " + e);
                 }
                 }
 } 

Output:

Before operation: [Java, Spring, Struts, MongoDB, Oracle]
After operation: [Java, Spring, Struts, Hibernate, Oracle]
Replaced element: MongoDB 



ADVERTISEMENT
ADVERTISEMENT