Linear Search in java

Linear Search is a simple searching algorithm that checks each element in a list one by one until it finds the target element or reaches the end of the list. It is also known as sequential search.

Here is an example of Linear Search in Java:

public class LinearSearch {
    public static int search(int[] arr, int x) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == x) {
                return i;
        return -1;

    public static void main(String[] args) {
        int[] arr = { 5, 10, 15, 20, 25, 30 };
        int x = 25;
        int result = search(arr, x);
        if (result == -1) {
            System.out.println("Element not found in the array.");
        } else {
            System.out.println("Element found at index " + result);

In this example, we define a search method that takes an array arr and a target value x as arguments. The method iterates over each element in the array and compares it with the target value. If the target value is found, the method returns the index of the element in the array. If the target value is not found, the method returns -1.

In the main method, we create an array arr and a target value x. We call the search method with these values and store the result in the result variable. Finally, we check if the result is -1 (indicating that the target value was not found) and print a message to the console accordingly.