Java Tutorial Index

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 Program to find and replace characters on string in java Program to find the duplicate characters in a string Program to check whether a given character is present in a string or not Java Program to Print Permutations of String Java program to find frequency of characters in a string Java Program to remove duplicate characters in a string

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 Methods 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 file Reader Java Buffer Reader Java file Writer Java BufferedWriter Java InputStreamReader Scanner in Java Java StringReader Java StringReader Class Java StringWriter Class Java PrintWriter Java File Java Read File Line By Line Java FileInputStream Java FileOutputStream Java Create File Java Delete File Java Open File Java Read File to String Java copy file Jar File in Java Java FileNotFoundException

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 Deque 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 JDBC Architecture Types of JDBC Drivers JDBC vs ODBC Java Database Connectivity with MySQL Java Database Connectivity with Oracle Statements in java Prepared statement in Java Resultset in java Java ResultSetMetaData DatabaseMetaData in Java Callable Statement in Java Transaction Management in Java Design of JDBC

Java Differences

Java vs DotNET Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Java float vs double Java vs Scala Java vs Go Java vs Golang Java Extends vs Implements Java vs Node.js Static vs Non-static in Java C vs Java int vs Integer in Java Java protected vs private Java vs Dot Net Stack vs Heap in Java Java Array vs ArrayList Java SE vs EE Class vs Object in Java Java vs Bedrock Difference between = = and equals ( ) in java Difference between C, C++, java HashMap Vs HashTable Checked vs Unchecked Exceptions in Java Difference between print() and println() in Java Differences between Lock and Monitor in Java Concurrency Differences between Set and List in Java How to calculate time difference in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Difference between String and Char Array in Java Differences between Byte Code and Machine Code Difference between String Tokenizer and split Method in Java Difference between JIT and JVM in Java Difference Between Data Hiding and Abstraction in Java Difference between String Tokenizer and Split Method in Java Difference Between BufferedReader and FileReader Difference Between Thread.start() and Thread.run()

How to

How to convert String to String array in Java How to find length of integer in Java How to get Day Name from Date in Java How to open the Java control panel How to resolve Illegal state exceptions in Java How to reverse a linked list in java How to encrypt password in Java How to calculate time complexity of any program in Java How to check version of java in Linux How to enable java in chrome 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 add double quotes in a string in Java How to convert list to String in Java How to call a method in Java How to Set Environment Variables for Java How to sort an array in Java How to Create Immutable Classes 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 Singleton Class 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 find the length of an Array in Java How to Read Java JSON file 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 import packages in Java How to run applet Program in Java How to take Array Input in Java How to achieve abstraction in Java How to call static method in Java How to compare characters in Java How to compare dates in Java How to create a linked list in Java How to download Eclipse for Java How to get ASCII value of char in Java How to get the current date and time in Java How to handle NullPointerException in Java How to initialize string array in Java How to Install Java on MAC How to run java program in ubuntu How to find characters with the maximum number of times in a string java How to Set Java_home in Linux How to Split the String in Java with Delimiter How to take Multiple String Input in Java using Scanner class How to uninstall the Java in Ubuntu How to Update Java How to add Elements in Array in Java How to avoid deadlock in java How to Split String by Comma in Java How to remove special characters from String in Java How to remove last character from String in Java How to Read XML Files in Java How to download and install Eclipse in Windows How to Create an API in Java How to Round Double Float up to Two Decimal Places in Java How to create a mirror image of a 2D array in Java How to set timer in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Type Annotations in Java Java Stringjoiner Class Parallel Arrays Sort in Java Bifunction in java 8 Java 8 filters list Java 8 Consumer Interface in Java

Java 9 Features

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

Java 12

What’s new in Java 12

Java 13

Java 13 New Features

Java 14

New Features of Java 14

Java 15

What’s New in Java 15

Java 16

Java 16

Java 17

What is new in Java 17

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hiberate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial Jenkins java net socket connection time out

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.fma() 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

List all files in a Directory in Java Nonagonal number in Java Null Pointer Exception in Java Package naming convention in Java Packages Program in java Pangram Program in Java PriorityBlockingQueue Class in Java Race Condition in Java Repdigit Numbers in Java Reserved Keywords in Java Rotate matrix by 90 degrees in Java Segment Tree in Java Sierpinski Number in Java Sort Dates in Java Thread Safety and How to Achieve it in Java Normal and Trace of a Matrix in Java Transient variable in Java Tribonacci series in Java Web Crawler in Java Zigzag Traversal of Binary Tree in Java Java Full Stack Java IO filenotfoundexception Java Output Formatting Java Plot Java Pop Java program to print matrix in Z form Java Set to List Java Switch string Java Thread Lifecycle: States and Stages Java Viva Questions and Answers Lazy Propagation in Segment Tree in Java Level order Traversal of a Binary Tree in Java Method chaining in Java Narcissistic Number in Java Java Case Keyword Java Try-Catch Block Java Class KeywordJava concurrency interview questions Java Continue Keyword Java CountDownLatch Java Default Keyword Java Double Keyword Java Editors Java Else Keyword Java Enum Keyword Java Extends keywordJava Finally Keyword Java Font Example of Static import in Java How Many Ways to Create Objects in Java Implementing Queue Using Array in Java Instanceof operator in Java Interchange Diagonal elements in Java Java Arrays Fill Java Char Keyword Convert list to array Java Convert milliseconds to date in Java Copy data/content from one file to another in java CRC Program in Java Creating a Jar file in Java Crown Pattern in Java Difference Between Access Specifiers and Modifiers in Java Difference Between Java and PHP Difference Between replace() and replaceall() in Java Duodecimal in Java Finding middle node of a linked list in Java Group by in Java 8 Hollow Diamond Pattern in Java How annotations work in Java Java Boyer Moore Catalan number in Java Cosmic Superclass in Java Difference between this and super in Java Fall through in Java Figurate Number in Java Java Anon Proxy Java RMI Lazy loading in Java Magnanimous Number in java Shallow copy in Java String to JSON in Java Tetranacci Number in Java Vigesimal in Java Why main method is static in Java Add Time in Java Bellman Ford Algorithm in Java Best Java Libraries Blockchain in Java Blocking Queue in Java Example Bully Algorithm code in Java Contextual keywords in Java Convert JSON File to String in Java Determine the Upper Bound of a Two-Dimensional Array in Java Java.net.ConnectionException Java.net.SocketException Web Service Response Time Calculation in Java 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 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 stop execution after a certain time in Java Jagged Array in Java Java ArraylistRemove() Time Complexity Java Swing Time Picker Zigzag Array in Java Array and String based questions in Java Array and String with Examples in Java Best Practices to use String Class in Java What is string in Java why it's immutable Java String Java String Inbuilt functions Java String Matches vs Contains Sum of digits in string in java Check the presence of Substring in a String in java Java import packages Interfaces and Classes in Strings in Java Maximum length of string in java Hidden classes in Java Class memory in Java public static void main string args meaning in java Reverse a String in Java String Concatenation in Java Buffer reader to read string in Java Split String into String Array in Java Reverse a String using Collections in Java Upcasting and Downcasting in Java String Declaration in Java Method Overloading In Java Java Solid Principles Java Architecture Binary Search Java Star Program in Java Java Type Casting Java Pass-by-Reference Java Framework List Java Destructors Java Control Statements Java Byte Code Java Beans Java Identifiers Character Array in Java Java Applications Java Substring Java Session Non-primitive data types in Java Matrix Multiplication in Java JIT in Java Java Tokens Java Externalization Default Virtual Behaviour in C++ vs Java Why we use static in Java Session Tracking in Java Knapsack problem in Java Java Logo Java exception list Java Iterator Java instance variable Frugal number in Java Fork Join in Java Date time API in java Compile time vs Runtime in java Compare time in java AES 256 Encryption in Java Advanced Java skills What is advance Java? User Defined Exception in Java Upcasting in Java Tree Implementation in Java Special Operators in Java Reentrant Lock in Java Perfect Number in Java Java logger Java LinkedList vs ArrayList File Operation in Java Constructor Overloading in Java Conditional operator in Java Concurrent Linked Deque in Java with Examples Command Class in Java Java Break Keyword Best Java IDE Association in Java Access specifiers in Java AbstractSet Class in Java Adapter class in Java Composition in Java Mutable and Immutable in Java Static() Function in Java Traverse through HashMap in Java Vectors in Java Creation of Multi Thread in java Java Enumeration Compile-time Error in Java Java Get Time in UTC Java.sql.Time Format Structure of Java Program Thread Concept in Java Creation of Multi-Thread in Java Enterprise Java Beans POJO in Java Volatile keyword in Java Java Constant Collection Interfaces in Java with Examples Deadlock Prevention and avoidance in Java Java Boolean Keyword Java Byte Keyword Java List Implementations Java Xml Parser Method Overriding in Java RMI program in Java Virtual Function in Java What is interpreter in Java? Advanced Java Viva Questions Application of Array in Java Economical number in Java Iterate JSON array in Java Java callable example Java Command not found Java Date add Days Java File Extension Java Location Java Trim User Defined Custom Exceptions in Java Java array list remove time complexity Java.lang.Exception.NoRunnableMethods Java Map Example Java Obfuscator Java Pi Java Queue Java time local date Java Xmx Uses of Java Applet Life Cycle in Java Best Java Security Framework BigDecimal toString() in Java Jdoodle Java Literals in Java MVC in Java Powerful Number in Java Read the XLSX file in Java Relatively Prime in Java Root exception in java What is anagram in Java? Accessors and Mutator in Java Bottom view of a binary tree in Java Convert List to String in Java Equidigital in Java How to check data type in Java IdentityHashMap in Java Java Clone Array Java LDAP Authentication Java List Node Java Password Generator Magic Square in Java Pancake Sorting in Java Practical Number in Java Sublime Number in Java Sudoku in Java Compare Two Times in Java Diffie Hellman Algorithm in Java How to Reduce Time Complexity in Java Java calculate age Map of Map in Java Minimum XOR value pair in Java Palindrome Partitioning problem in Java Pernicious Number in Java Prime Points in Java Rectangular Numbers in Java Sleep Time in Java The final Keyword in Java Types of Statements in Java Unicode System in Java Zig Zag star and Number Pattern in Java Balanced Prime Number in Java ConcurrentSkipListSet in Java Construct the Largest Number from the Given Array in Java CopyOnWriteArrayList in Java Cyclic Barrier in Java Dangling Else problem in Java Display Unique Rows in a Binary Matrix in Java Empty Statement in Java Factorial of a Large Number in Java Facts about null in Java Rehashing in Java Singleton Design Pattern in Java Zebra Puzzle Problem in Java XOR of Array Elements Except Itself in Java Types of Sockets in Java Thread Synchronization in Java Set Up the Environment in Java Method and Block Synchronization in Java Fibodiv Number in Java House Numbers in Java GCD of Different SubSequences in Java Hogben Numbers in Java Decagonal Numbers in Java Converting Roman to Integer Numerals in java Check if the given array is mirror inverse in Java Caesar Cipher Program in Java Block Swap Algorithm for array rotation in Java Java Binary Tree Binary Strings Without Consecutive Ones in Java Beautiful Array in Java Balanced Parentheses in Java Arithmetic exception in Java Add numbers represented by Linked Lists in Java Two Decimal Places Java Intersection Point of two linked list in Java Find next greater number with same set of digits in Java Getter and Setter Method in Java Example Java Binary to Hexadecimal Java Calculate Average of List Iccanobif Numbers in Java Java delete directory Java For Keyword Java Float Keyword Java Instanceof Keyword Java If Keyword Java Int Keyword Java Import Keyword Java Package Keyword Java Static Keyword Java Public Keyword Java Implements Keyword Java Private keyword Java Protected Keyword Java Short Keyword Java Long Keyword Java Interface Keyword Java Try Keyword Java New Keyword Java Return Keyword Tug of War in Java Types of Events 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