5. Write a Java program to test if the first and the last element of two array list of integers are same
Please find the Java code for the following:
Code:
import java.util.ArrayList;
public class ArrayListOperations {
public static void main(String[] args) {
//creating two Empty Integer
ArrayList
ArrayList<Integer> list1 = new
ArrayList<Integer>(5),list2 = new
ArrayList<Integer>(5);
//We are using add() to initialize values in list1
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(1);
//We are using add() to initialize values in list2
list2.add(4);
list2.add(3);
list2.add(2);
list2.add(1);
//Here, we need to Fetch the first and the last element of two
array list
//Get the first and last elements from list1
//and store them in first1 and last1 variables
int first1=list1.get(0);
int last1=list1.get(list1.size()-1);
//Get the first and last elements from list2
//and store them in first2 and last2 variables
int first2=list2.get(0);
int last2=list2.get(list2.size()-1);
//Check if the first and the last element of array list of integers
are same in list1
if(first1==last1)
System.out.println("First and last elements are same
in First list");
else
System.out.println("First and last elements are not
same in First list");
//Check if the first and the last element of array list of integers
are same in list2
if(first2==last2)
System.out.println("First and last elements are same
in Second list");
else
System.out.println("First and last elements are not
same in Second list");
}
}
Please check the compiled
program and its output for your reference:
Output:
(I believe that I made the code simple and understandable. If you still have any query, Feel free to drop me a comment)
Hope this Helps!!!
Please upvote as well, If you got the answer?
If not please comment, I will Help you with that...
Get Answers For Free
Most questions answered within 1 hours.