1

Can i have two or more public static void main(String args[]) method in **diffrent classes but same package **

I am new to java as well as stackoverflow.So sorry for any ignorance in advance.

I tried to put two classes with public static void main(String args[]) method in same package but on compiling one of the class there was an error "Could not find or load main class BinarySearch".

so my question is why can't we declare two main method in different classes when it is valid to declare other methods in different classes with same name??

code for first class

package geeksforgeeks;
class BinarySearch
{
// Returns index of x if it is present in arr[l..
// r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
    if (r>=l)
    {
        int mid = l + (r - l)/2;

        // If the element is present at the 
        // middle itself
        if (arr[mid] == x)
           return mid;

        // If element is smaller than mid, then 
        // it can only be present in left subarray
        if (arr[mid] > x)
           return binarySearch(arr, l, mid-1, x);

        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid+1, r, x);
    }

    // We reach here when element is not present
    //  in array
    return -1;
}

// Driver method to test above
public static void main(String args[])
{
    BinarySearch ob = new BinarySearch();
    int arr[] = {2,3,4,10,40};
    int n = arr.length;
    int x = 10;
    int result = ob.binarySearch(arr,0,n-1,x);
    if (result == -1)
        System.out.println("Element not present");
    else
        System.out.println("Element found at index " + 
                                             result);
}
}

code for second class in same package

 package geeksforgeeks;

 import java.util.Scanner;

class LinearSearch{
  public static void main(String args[]){
  Scanner in = new Scanner(System.in);
  int [] a = new int[5];
  for(int i=0;i<5;i++)
    a[i]= in.nextInt();

   System.out.println("enter number to be found");
   int key = in.nextInt();

  for(int i=0;i<5;i++){
    if(a[i]==key){
    System.out.println("number is present");
    break;
  }
  if(i==4)
    System.out.println("number is not present");
}
 }
 }

and the terminal output is

C:\Users\ayush\Desktop\java\geeksforgeeks>javac BinarySearch.java

C:\Users\ayush\Desktop\java\geeksforgeeks>java BinarySearch
Error: Could not find or load main class BinarySearch
Ayush Aggarwal
  • 177
  • 3
  • 12

1 Answers1

3

The class BinarySearch is in package geeksforgeeks. To start it, your current directory needs to be c:\Users\ayush\Desktop\java and you must use the command line:

C:\Users\ayush\Desktop\java>java geeksforgeeks.BinarySearch

Alternatively, instead of changing the current directory, you can also specify the class path when you start it.

Henry
  • 42,982
  • 7
  • 68
  • 84