Search code examples
javaarraysarraylistprogram-entry-point

How to initialize a string array in a main Java method


I have written some code which creates and initializes a String ArrayList. Is it possible to declare the arguments directly in to the String [] args method itself, rather than creating an extra String arrayList?

public class sampleCode{
    public static void main(String[] args ) {

    String[]args2 = {"en", "es"};

        if( args2[0].equals("en")) {
            System.out.println("english option");
        }
        else if( args2[1].equals("es")) {
            System.out.println("spanish option");
        }
        else System.out.println("this is the default option");
    }
}

Solution

  • Firstly, It was difficult to understand your request, but I get it finally.

    The answer of your request is YES. Yes it is possible to not create an extra array of String in your code. In this case, you need to enter the options en and es using the command line.

    Here is how to update your code:

    public class SampleCode { 
    
      public static void main(String[] args ) {
    
      //String[]args2 = {"en", "es"};
    
      if( args[0].equals("en")) {
        System.out.println("english option");
     }
     else if( args[1].equals("es")) {
        System.out.println("spanish option");
     }
     else { System.out.println("this is the default option");}
    
     }
    }
    

    Now, here is the process:

    1. In your terminal, compile your code : javac SampleCode.java
    2. And execute it by giving the arguments: java SampleCode "en" "es"

    It is a possible manner to do what you need. But in this case, english option will always be obtained.

    Hope, it helps you.