Search code examples
javastaticprogram-entry-point

How should I use Main and static for this block of code?


I have a question regarding these two blocks of code: The first one:

class Solution {
public  int[] twoSum(int[] nums, int target) {
 int[] result= new int[2];
 for (int i=0; i<nums.length; i++){
    for (int j=i+1; j<nums.length; j++){
         if ( nums[i]+nums[j]==target){
            result[0]=i;
            result[1]=j;
         }
     }
 }
 return(result);
 }
}

and the second one:

import java. util.*;

public class Solution {

public static int firstUniqChar(String s) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    
    String[] s_arr = s.split("");

    for (int i = 0; i < s_arr.length; i++) {
        if (map.containsKey(s_arr[i])) {
        
            map.put(s_arr[i], map.get(s_arr[i]) + 1);
        }
        else
            map.put(s_arr[i], 1);
    }
    
    for (int i = 0; i < s_arr.length; i++) {
        if (map.get(s_arr[i]) == 1) {
            return i;
        
        }
    }
    return -1;
}

public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    System.out.println(firstUniqChar(sc.nextLine()));

}   

}

My question is why and how the first code is working without "main"!! And if I want to put "main" for the first code how should I do that? I follow the pattern of the second code regarding static and main and.. but it does not work. Thanks


Solution

  • Add this to the first definition of Solution and run it:

    public static void main(String[] args) {
        
        Solution sol = new Solution();
        System.out.println(sol.twoSum(new int[]{1,2,3}, 4));
    
    }   
    

    For any Java program to run it requires a main method with signature as follows. It’s the entry-point or start point. If it’s not in your code it is provided by the surrounding code - online or IDE.

    public static void main(String[] args)
    

    Any static method (firstUniqChar) can be called without referring to an object. A non-static method (twoSum) is linked to an object so has to be invoked from an object, in this case sol