Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main() arguments in java

I'm trying to write a code for a program that recives strings as an input. The program prints "Error" when the user does not put any data, otherwise it prints the first string argument.

Is it right to refer to no data as a "null"? It does not work. what should I write instead?

public class Try {
public static void main(String[] args){
    if (args[0]==null){
        System.out.println("Error- please type a string");
    }else {System.out.println(args[0]);}

    }
}
like image 244
Unknown user Avatar asked Nov 30 '22 08:11

Unknown user


1 Answers

Arguments will never be null if they exist in the first place -- to check that, you should use args.length instead:

if (args.length == 0) {
  ...
} else {
  ...
}
like image 110
casablanca Avatar answered Dec 07 '22 22:12

casablanca