• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 391
  • Last Modified:

JAVA ternary operator as a check for command line args


I'm coming from a javascript background, so it's possible that what I'm trying to do is not really a good way to do the same in JAVA.

I'd like to use some command line arguments to set up some values in my program. If the values are not supplied, I'd like to have default values.

this line works just fine:
int testIterations = Integer.parseInt(args[0]);

Open in new window

but I would like to do something like this, which is not compiling
int testIterations = Integer.parseInt(args[0]) != undefined ? Integer.parseInt(args[0]) : 50;

Open in new window

here's the error:
error: cannot find symbol
		int testIterations = Integer.parseInt(args[0]) != undefined ? Integer.parseInt(args[0]) : 50;
  symbol:   variable undefined
  location: class MyClass

Open in new window

if I use null instead of undefined, I get this error:
error: incomparable types: int and <null>
		int testIterations = Integer.parseInt(args[0]) != null ? Integer.parseInt(args[0]) : 50;

Open in new window

Kyle Hamilton
Kyle Hamilton
  • 2
1 Solution
why not just compare args[0] against null?  If null, no parameters.
        int testIterations = (args.length >= 1) ? Integer.parseInt(args[0])
                                                : DEFAULT_ITERATION_COUNT;

Open in new window

would do it
Kyle HamiltonData ScientistAuthor Commented:
thanks CEHJ.

Do you know if there is a good solution out there for creating flags?
(from my search online, JAVA doesn't appear to have this capability natively, like C)

so I could do something like this:

java MyClass -t50 -d100

any ideas? (let me know if you want me to open a new question)
Yes, a new question is necessary
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now