I would like to know to know how do i compare the arguments passed into a java main method.
eg java hello -i
I tried printing args[0] and it does indeed gives me -i. however what i want to achieve is:
if args.length == 0 {
do something
}
else if args[0] =="-i"{
do something
}
However i keep getting index out of bound exception. is there anyway to convert the string in the string array args to just a string type so i can compare it?
public static void main(String[] args) {
if args.length == 0 {
do something
}
else if args[0] =="-i"
do something
}
}
for example if they start the program without any arguments, i will call init() method. but if they entered -i as arguments, i will call install() instead..
The code you’ve given wouldn’t even compile, but this does work:
Note that it’s important that you’re using
elsehere – this would fail, for example:at that point you’re checking
args[0]even if the length of the array is 0. Given that you’ve given pseudo-code at the moment (no brackets round the conditions) I wonder whether that’s the problem in your real code.(Also note the use of
equalsinstead of==as others have already pointed out.)