Search code examples
javainner-classes

Is it fine to put a class inside the main class in Java?


I want to know whether it is fine to put a class inside a Main class as the code snippet shown below? This code works fine but just want to make sure whether this is correct or not,
putting a class in static way inside the main class without making a making whole separate class.
For example;



    public class Main {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            LinearSearch ls = new LinearSearch();
    
            int[] arr = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2};
            System.out.println("Element to be found: ");
            int x = sc.nextInt();
            ls.linearSearch(arr, x);
    
        }
        public static class LinearSearch {
            int linearSearch(int[] arr, int target) {
                for(int i=0;i<arr.length;i++) {
                    if(arr[i] == target) {
                        System.out.println("Item found at = "+(i+1));
                    }
                }
                return -1;
            }
        }
    }


Solution

  • If you create a class or a method it's because you need to use the same code elsewhere, if you need to do it I suggest you putting that code in a LinearSearch class file or transforming it into a public static method (with static methods you can call it without declaring the object, like Main.linearSearch(arr,target)) else if you need to use it only once as in your code you can transform it in a private method or simply putting the code you need instead of using a method.

    Also, as i see, the returned value isn't used, so you can transform it into a void function.

    Like this:

    public class Main {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            int[] arr = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2};
            System.out.println("Element to be found: ");
            int x = sc.nextInt();
            linearSearch(arr, x);
        }
    
        private static void linearSearch(int[] arr, int target) {
            for(int i=0;i<arr.length;i++) {
                if(arr[i] == target) {
                    System.out.println("Item found at = "+(i+1));
                }
            }
        }
    }