w3resource

Java: Test if the first and the last element of an array of integers are same

Java Basic: Exercise-75 with Solution

Write a Java program to test if the first and last elements of an array of integers are the same. The array length must be broader than or equal to 2.

Sample Solution:

Java Code:

import java.lang.*;

public class Exercise75 {
    public static void main(String[] args) {
        // Define an integer array
        int[] num_array = {50, -20, 0, 30, 40, 60, 10};
        
        // Check if the array has at least 2 elements and if the first and last elements are equal
        boolean result = (num_array.length >= 2 && num_array[0] == num_array[num_array.length - 1]);

        // Print the result
        System.out.println(result);
    }
}

Sample Output:

false

Pictorial Presentation:

Java exercises: Test if the first and the last element of an array of integers are same
Java exercises: Test if the first and the last element of an array of integers are same

Flowchart:

Flowchart: Test if the first and the last element of an array of integers are same

Java Code Editor:

Previous: Write a Java program to test if 10 appears as either the first or last element of an array of integers.
Next: Write a Java program to test if the first or the last elements of two arrays of integers are same.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/basic/java-basic-exercise-75.php