Write a Java program to retrieve an element from a given array list


This is a Java program that retrieves elements from an ArrayList using the get method. Here's how the program works:

  • The program creates an ArrayList of Strings, named list_str, and initializes it with some values.
  • The program prints the contents of list_str using System.out.println.
  • The program uses the get method to retrieve the first element of list_str and assigns it to the variable ele.
  • The program prints the value of ele using System.out.println.
  • The program uses the get method again to retrieve the fifth element of list_str and assigns it to the variable ele.
  • The program prints the value of ele again using System.out.println.

Source Code

import java.util.*;
class Retrieve_Element
{
	public static void main(String[] args)
	{
		List<String> list_str = new ArrayList<String>();
		list_str.add("Laptop");
		list_str.add("Keyboard");    
		list_str.add("Mouse");
		list_str.add("CPU");
		list_str.add("Printer");
		list_str.add("Derive");
		list_str.add("Monitor");
		System.out.println(list_str);
		String ele = list_str.get(0);
		System.out.println("First Element: "+ele);
		ele = list_str.get(4);
		System.out.println("Fifth Element: "+ele);
	}
}

Output

[Laptop, Keyboard, Mouse, CPU, Printer, Derive, Monitor]
First Element: Laptop
Fifth Element: Printer

Example Programs